0

我有以下课程:

@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;
  }
  //....
  //....
}

我想保存ClassAClassB仅在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它是否存在并加载它,但我想提高效率。

4

1 回答 1

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);
     }
于 2012-09-13T19:24:55.070 回答