【问题标题】:JPA, flush and Entity Manager syncJPA、刷新和实体管理器同步
【发布时间】:2013-01-22 15:08:51
【问题描述】:

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

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

(脚本A)现在,我执行这个sn-p:

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 或重新加载我的应用程序并执行这些 sn-ps,我的计数 = 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);

【问题讨论】:

  • 或许值得在 gardenFacade.create() 后面插入代码
  • 好的,但是是一个简单的persist()调用:getEntityManager().persist(entity);
  • 看看这个great article的主题。

标签: database jpa relationship entitymanager


【解决方案1】:

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

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

【讨论】:

  • 正如这里所指的,您需要正确的对象模型正确的数据库。因为它是你不设置一对多(集合)。您需要将对象添加到集合中,就像您在脚本 B 的更改中所做的那样
猜你喜欢
  • 2015-03-08
  • 2020-11-07
  • 1970-01-01
  • 2012-03-14
  • 2015-10-30
  • 2015-06-14
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多