When does EntityManager commit?

I have the following service ...

@Stateless @LocalBean public class RandomService { @EJB RandomString stringTokenizer; @PersistenceContext EntityManager em; public String generate(Actions action) { Token token = new Token(); token.setAction(action); token.setExpiry(new Date()); token.setToken(stringTokenizer.randomize()); em.persist(token); //em.flush(); return String.format("%010d", token.getId()) + token.getToken(); } } 

If I don't put em.flush (), then the token.getId () line will return null (using DB GENERATED SEQUENCE), although I know if the token will be returned instead of the line in the calling service set by id. Thus, it seems that EM is reset when the service returns a token object, but not when I put the String. Putting a flash, I get what I need, is it true, though?

+4
source share
1 answer

Do not confuse flushing with fixation. During flush() JPA provider physically sends the generated SQL to the database and, in your case, reads the generated identifier and populates it into the bean. Note that you should always use the return object, not the original one that was passed to persist() :

 token = em.persist(token); 

Strike>

On the other hand, committing a transaction with a database commit. Obviously, it will call flush() , but that will not help you. But since you ask - every method in EJB is transactional by default. This means that the transaction is committed when you leave the first EJB on the stack: if you call one EJB from another, the caller joins the caller’s transaction by default (see Transaction Behavior).

Also note that the rules when flush() bit complicated, as each provider tries to do this as late as possible and in packages.

+7
source

All Articles