2

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));
joekarl
  • 2,118
  • 14
  • 23

1 Answers1

10

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).

axtavt
  • 239,438
  • 41
  • 511
  • 482