title: Hibernate: Save the reference if it does not exist
body: <p>I have the following classes:</p>
  
  <pre><code>@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;
    }
    //....
    //....
  }
  </code></pre>
  
  <p>I want to save <code>ClassA</code> and save <code>ClassB</code> only if <code>ClassB</code> does not exist yet.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>Ofcourse I can check <code>ClassB</code> if it exists and load it but I want to do it more efficient.</p>