有关在调用查询之前使用JPA进行刷新的问题 [英] Question about flushing with JPA before a query is called
问题描述
只是一个简单的问题,但这段代码中是否需要刷新?请注意,这将在JPA交易中。
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));
推荐答案
在第一种情况下,只要需要刷新用户
具有自动生成的ID,因为它在刷新之前未分配。如果未生成 id
, em.find()
将从持久化上下文返回相同的实例,因此不需要刷新。
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.
在第二种情况下,不需要显式刷新,因为JPA执行在自动执行查询之前刷新(如果刷新模式是 AUTO
,则默认情况下,否则需要显式刷新。)
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).
这篇关于有关在调用查询之前使用JPA进行刷新的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!