JPA,flush和Entity Manager同步

时间:2013-01-22 15:08:52

标签: database jpa relationship entitymanager

我正在使用Java EE,Netbeans和Facade会话bean来实现JPA层(eclipselink)。

我有一张两张桌子例如:Garden(1)--->树(n)。

(脚本A)现在,我执行这个片段:

Garden mGarden = new Garden();
.....
gardenFacade.create(garden)

(剧本B)然后:

Tree oneTree = new Tree();
oneTree.setGarden(mGarden);
treeFacade.create(oneTree);

通过这种方式,实体树被正确添加到我的数据库中,外键是正确的。

(脚本C)当我调用时:

Garden findGarden = gardenFacade.find(gardenId);
int count = findGarden.getTreeCollection().size();

我算了= 0 !!! 如果我重新启动glassfish或重新加载我的应用程序并执行这些片段,我会计算= 1。

所以,我认为这是持久性上下文同步的问题,因为如果我改变我的脚本B:

Tree oneTree = new Tree();
oneTree.setGarden(mGarden);
treeFacade.create(oneTree);

mGarden.getTreeCollection().add(oneTree);
gardenFacade.edit(mGarden);

一切正常! 我该如何解决这个问题?

编辑:

create --> getEntityManager().persist(entity);
edit ----> getEntityManager().merge(entity);
find ----> getEntityManager().find(entityClass, id);

1 个答案:

答案 0 :(得分:0)

看起来所有这些调用都使用相同的hibernate会话,并且你无法正确初始化集合的两面,当然你在集合中没有得到任何东西:

Garden mGarden = new Garden(); // create a new Garden instance
session.persist(mGarden); // now this Garden instance is persistent. 
                          // Its state will be written to the database at the 
                          // next flush
Tree oneTree = new Tree(); // create a new Tree instance
oneTree.setGarden(mGarden); // set the garden of the tree. This is a basic, simple 
                            // Java method call. Nothing will magically add the tree
                            // to the garden collection of trees if you don't do 
                            // it explicitely
session.persist(oneTree); // now this Tree instance is persistent. 
                          // Its state will be written to the database at the 
                          // next flush. 
Garden findGarden = session.get(Garden.class, gardenId); 
    // returns the garden that has the specific ID. It's already in the session: 
    // you created and attached it to the session at the beginning. And you 
    // never added anything to its collection of trees