为啥 Eclipselink 不在单向 @ManyToOne 关系中生成 ON DELETE CASCADE 子句?
Posted
技术标签:
【中文标题】为啥 Eclipselink 不在单向 @ManyToOne 关系中生成 ON DELETE CASCADE 子句?【英文标题】:Why doesn't Eclipselink generate the ON DELETE CASCADE clause in a unidirectional @ManyToOne relationship?为什么 Eclipselink 不在单向 @ManyToOne 关系中生成 ON DELETE CASCADE 子句? 【发布时间】:2014-08-01 15:01:10 【问题描述】:这是 Eclipselink JPA 中的两个相关实体:
@Entity
public class Department
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@Entity
public class Person
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
@ManyToOne(cascade=CascadeType.ALL)
private Department department;
这是生成的 DDL:
CREATE TABLE PERSON (ID BIGINT IDENTITY NOT NULL, FIRSTNAME VARCHAR, LASTNAME VARCHAR, DEPARTMENT_ID BIGINT, PRIMARY KEY (ID))
CREATE TABLE DEPARTMENT (ID BIGINT IDENTITY NOT NULL, NAME VARCHAR, PRIMARY KEY (ID))
ALTER TABLE PERSON ADD CONSTRAINT FK_PERSON_DEPARTMENT_ID FOREIGN KEY (DEPARTMENT_ID) REFERENCES DEPARTMENT (ID)
环境是: - eclipselink 2.5.2 - mysql-connector-java 5.1.6
我希望在外键定义上至少有一个 ON DELETE CASCADE 子句。 在@ManyToOne 关系中,级联选项的用途是什么? 我真的必须在删除父记录之前手动删除子记录吗?
【问题讨论】:
重复帖子:***.com/questions/7197181/… 在 EclipseLink 中,您将指定 @CascadeDelete 注释来告诉它应该在数据库级别自动删除关系,如此处所述wiki.eclipse.org/EclipseLink/Examples/JPA/DeleteCascade 【参考方案1】:您在示例中提到的CascadeType
是其中一个值:ALL, PERSIST, MERGE, REMOVE, REFRESH, DETACH
。这是ORM
,但与 SQL DDL 无关。
我猜您正在搜索 SQL DDL 外键约束定义...on delete cascade
。要生成此 SQL DDL,您需要一个 @CascadeOnDelete
注释,如下例所示:
...
@OneToMany(mappedBy="abc", orphanRemoval=true, cascade=CascadeType.ALL)
@CascadeOnDelete
private List<MobilPhoneNumer> mobilePhonesNumbers;
...
【讨论】:
以上是关于为啥 Eclipselink 不在单向 @ManyToOne 关系中生成 ON DELETE CASCADE 子句?的主要内容,如果未能解决你的问题,请参考以下文章
为啥eclipselink每次重新启动时都会消耗整个allocationSize?