我有一個類A
可以具有一個關聯到多個B
秒(一到多):休眠一個一對多關聯保存重複
@Entity
@Table(name = "a")
public class A implements Serializable {
private static final long serialVersionUID = 6796905221158242611L;
@Id
@GeneratedValue
@Column(name = "a_id")
private Long a_id;
@Column(name = "name")
private String name;
@OneToMany(mappedBy = "a", cascade = CascadeType.ALL)
private Set<B> bs;
public void addB(B b) {
if(bs == null)
bs = new HashSet<B>();
bs.add(b);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
和類B
存儲參考到A
:
@Entity
@Table(name = "b")
public class B implements Serializable {
private static final long serialVersionUID = 6063558165223241323L;
@Id
@GeneratedValue
@Column(name = "b_id")
private Long b_id;
@Column(name = "name")
private String name;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "a_id")
private A a;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public A getA() {
return a;
}
public void setA(A a) {
this.a = a;
}
}
現在當我執行下面的代碼Hibernate會保存在具有名稱b1
表b
兩個兩個條目。我不知道如何避免這個或我做錯了什麼。
EntityManagerFactory emf = Persistence.createEntityManagerFactory(Configurations.MYSQL);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
A a1 = new A();
a1.setName("a1");
A a2 = new A();
a2.setName("a2");
B b = new B();
b.setName("b1");
a1.addB(b);
a2.addB(b);
em.merge(a1);
em.merge(a2);
em.getTransaction().commit();
合併A1和A2,然後B,然後將B添加到As中。這實際上應該可行。 – sorencito