我正在使用JPA和Hibernate作为MySQL DBMS的提供者,我注意到级联删除不适用于我的情况:
@Entity
public class Entity_1{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nomAttribute;
@ManyToMany(cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private java.util.List<Entity_2> et2;
...
}
,第二个实体是
@Entity
public class Entity_2{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String nomAttribute;
...
}
结果是三个表
Entity_1,Entity_2,Entity_1_Entity_2
我注意到当我删除Entity_1时,由于删除级联而导致Entity_2被删除。
我想要的是当我删除Entity_1时,Entity_1和Entity_2之间的关系只删除了Entity_2而我尝试了很多选项,但都是徒劳的
我应该使用什么选项,或者没有选项,我应该使用触发器?
答案 0 :(得分:1)
Class Entity1:
@Entity
public class Entity1 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, mappedBy = "entity1")
private Collection<Entity1Entity2> collection;
...
}
类实体2:
@Entity
public class Entity2 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, mappedBy = "entity2")
private Collection<Entity1Entity2> collection;
...
}
Class Entity1Entity2(连接表):
@Entity
@IdClass(Entity1Entity2Pk.class)
public class Entity1Entity2 {
@ManyToOne
@Id
private Entity1 entity1;
@ManyToOne
@Id
private Entity2 entity2;
...
}
Class Entity1Entity2Pk(Entity1Entity2
所需):
public class Entity1Entity2Pk {
private int entity1;
private int entity2;
}
我添加了mappedBy = "entity1"
和mappedBy = "entity2"
。
这样@oneToMany
个关联就不会创建额外的连接表。