问题
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