0

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

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

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

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

(脚本 B)然后:

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

这样,实体Tree就被正确的添加到我的数据库中了,而且外键是正确的。

(脚本 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);
4

1 回答 1

0

看起来所有这些调用都使用相同的休眠会话,并且由于您未能正确初始化集合的两侧,当然您在集合中没有得到任何东西:

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
于 2013-01-22T16:00:05.103 回答