Question about flushing with JPA before a query is called

六眼飞鱼酱① 提交于 2020-01-11 03:41:05

问题


Just a quick question, but is the flush necessary in this code? Note this would be inside of a JPA transaction.

User user = new User();
em.persist(user);

em.flush;

User aUser = em.find(User.class,user.getId());
assert(user.equals(aUser));

Or is will it work without the flush?

User user = new User();
em.persist(user);

User aUser = em.find(User.class,user.getId());
assert(user.equals(aUser));

Or same question but a little more involved example:

User user = em.find(User.class,id);
user.setName("My Name");
em.merge(user);

em.flush; //Is this line needed?

User aUser = em.createQuery("select u from User where u.name = 'My Name');
assert(user.equals(aUser));

回答1:


In the first case flush is needed as long as User has an autogenerated id, since it's not assigned before flush. If id is not generated, em.find() will return the same instance from the persistence context, so flush is not needed.

In the second case explicit flush is not needed because JPA performs flush before executing a query automatically (if flush mode is AUTO that is by default, otherwise explicit flush is needed).



来源:https://stackoverflow.com/questions/4415211/question-about-flushing-with-jpa-before-a-query-is-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!