问题
how can I force the EJB to not flush everything after every single command, I want to do a transaction. I've read that this is done somehow declaratively. But how exactly?
@Stateless
public class SomeBean{
@PersistenceContext
EntityManager em;
public void doSomeStuffAndThenFlushToTheDb(){
em.persist(entity);
// it's flushed by now, I don't want that
em.persist(somethingElse);
// now I want to flush both
em.flush();
}
}
回答1:
Hi, how can I force the EJB to not flush everything after every single command, I want to do a transaction.
First of all, you shouldn't get a flush
after "every single command" and I'm actually surprised that you get a flush
after the persist
. Are you showing all the code? Second, EJB methods are transacted by default. But transaction and flush
are not really related (the only link is that a flush
will be done before the commit
). Anyway...
If you would like to control the way a flush()
call executes, you can change the default flush mode using EntityManager#setFlushMode()
. The flush modes are as follows:
COMMIT
- Flushing occurs only at transaction commit, or when flush() is called.AUTO
- (Default) Flushing occurs before any query execution.
So something like that should work:
@Stateless
public class SomeBean {
...
public void doSomeStuffAndThenFlushToTheDb(){
em.setFlushMode(COMMIT);
em.persist(entity);
em.persist(somethingElse);
em.flush(); // Causes flush
}
...
}
But as I said, I'm surprised by your example. The behavior you describe is not what I would expect.
回答2:
First of all "flush" means only store it the second level cache (db driver). It is not stored directly within the DB. The entity is kept within the cache since the transaction is completed and a commit is sent. "Clear" means detach the entity. It does not mean clear the database. So afterwards you cannot persist this entity anymore. But the persist will still be done at the end of the transaction.
来源:https://stackoverflow.com/questions/3719376/declare-a-transaction-in-ejb-3-0