我使用JPA和Hibernate作为MySQL数据库管理系统的提供者,并指出级联删除不适用于我的情况:
@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,我尝试了许多选项,但都是徒劳的。
我应该使用什么选项,或者没有选项,而我应该使用触发器??
发布于 2014-05-21 20:12:54
这个解决方案呢?
类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;
...
}类Entity2 :
@Entity
public class Entity2 {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@OneToMany(cascade = { CascadeType.PERSIST, CascadeType.REMOVE }, mappedBy = "entity2")
private Collection<Entity1Entity2> collection;
...
}类Entity1Entity2 (即联接表) :
@Entity
@IdClass(Entity1Entity2Pk.class)
public class Entity1Entity2 {
@ManyToOne
@Id
private Entity1 entity1;
@ManyToOne
@Id
private Entity2 entity2;
...
}类Entity1Entity2Pk (Entity1Entity2Pk :** )
public class Entity1Entity2Pk {
private int entity1;
private int entity2;
}最新情况:
我添加了mappedBy = "entity1"和mappedBy = "entity2"。这样,@oneToMany关联就不会创建额外的连接表。
https://stackoverflow.com/questions/23791838
复制相似问题