[英]Hibernate not updating ManyToMany associations during session
我正在使用Hibernate 4.3.4來訪問Postgres數據庫。 我們有兩個實體通過ManyToMany Association鏈接。
代碼和關聯當前有效,因為在EntityA的集合中添加EntityB會在提交Session后自動將EntityA添加到EntityB的集合中。 但是,我遇到的問題是,當我嘗試處理EntityB的EntityAs時,它應該包含我剛剛創建的EntityA,EntityA不在該集合中(它是空的)。 示例代碼在這里:
@Entity
@Table(name = "entity_a")
public class EntityA {
private Set<EntityB> entityBs = new HashSet<EntityB>(0);
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "entitya_entityb",
joinColumns = { @JoinColumn(name = "entitya_id") },
inverseJoinColumns = { @JoinColumn(name = "entityb_id") })
public Set<EntityB> getEntityBs()
{
return entityBs;
}
public void setEntityBs(Set<EntityB> entityBs)
{
this.entityBs = entityBs;
}
}
@Entity
@Table(name = "entity_b")
public class EntityB {
private Set<EntityA> entityAs = new HashSet<EntityA>(0);
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "entitya_entityb",
joinColumns = { @JoinColumn(name = "entityb_id") },
inverseJoinColumns = { @JoinColumn(name = "entitya_id") })
public Set<EntityA> getEntityAs()
{
return entityAs;
}
public void setEntityAs(Set<EntityA> entityAs)
{
this.entityAs = entityAs;
}
}
/**
* HTTP REST Resource to create Entities and persist them. We do some basic logic when we create them to show the problem.
*/
@Path("/battleRhythm")
@Singleton
public class HttpResource
{
@POST
@Consumes("application/json")
public void createEntityA() {
Session hibernateSession = SessionFactory.getCurrentSession(); // SessionFactory specifics not included
hibernateSession.getTransaction().begin();
// Add an EntityB to the new EntityA
EntityA entityA0 = new EntityA();
EntityB entityB0 = new EntityB0();
entityA.getEntityBs().add(entityB0);
// Persist the new EntityA
EntityADao.getInstance().save(entityA0);
// Try to get this EntityA from EntityB
Set<EntityA> associatedEntityAs = entityB0.getEntityAs(); // Doesn't contain any EntityAs!
hibernateSession.getTransaction().commit();
}
}
這是問題:
當我保存EntityA0時,是否可以讓Hibernate自動將EntityA0添加到EntityB0的集合中,而不提交事務? 這可能嗎? 怎么樣?
警告:上面的例子沒有完全反映這一點,但是我們對兩個實體執行類似的操作,因此在傳統的Hibernate意義上使用“owner”(使用mappedBy =“”屬性配置)並不是一個理想的選擇。 我不想試圖說服每個人只在CreateEntityA()中使用EntityB.getEntityAs()。add(EntityB0)。 這太令人困惑了。
你沒有選擇。 必須有一個所有者方面,必須有一個反面。 維護協會的雙方都是你的責任:當你只添加A到B時,不要指望在A的B集合中有B(反之亦然)
現在,沒有禁止你有一個方法addB(B b)
內部的,增加了b
到A的集合B的, 而這增加了this
到B的集合作為的。 你當然也可以在B中使用addA(A a)
方法做同樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.