我有以下课程:
@Entity
public class ClassA {
@Column
@Id
private Long id;
@ManyToOne(cascade = javax.persistence.CascadeType.ALL)
@JoinColumn...
private ClassB classB;
public ClassA(ClassB classB){
this.classB = classB;
}
//....
//....
}
@Entity
public class ClassB {
@Column
@Id
private Long id;
@Column(unique=true) //important
private String name;
public ClassB(String name){
this.name = name;
}
//....
//....
}
我想保存ClassA
并仅在ClassB
尚不存在的情况下保存ClassB
。
ClassB b = new ClassB("myName");
ClassA a = new ClassA(b);
session.merge(a); // fine
ClassA a2 = new ClassA(b);
session.merge(a2); // problem with b
当然我可以检查ClassB
是否存在并加载它但我想更有效率。
答案 0 :(得分:1)
如果classB存在且classB被管理,则getEntityManager.contains(b)返回true。
ClassB b = new ClassB("myName");
if(getEntityManager.contains(b)){
ClassA a = new ClassA(b)
session.merge(a);
}
else{
session.merge(b);
ClassA a = new ClassA(b)
session.merge(b);
}