休眠:如果引用不存在,请保存它

时间:2012-09-13 18:39:38

标签: java hibernate merge

我有以下课程:

@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是否存在并加载它但我想更有效率。

1 个答案:

答案 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);
     }