views:

38

answers:

1

Hi, 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();
  }
}

A: 

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.

Pascal Thivent
em.setFlushMode(FlushModeType.COMMIT);em.persist(match); em.clear(); em.flush(); , I would expect nothing to be saved in the database in this concise example, but the oposite is the truth, why? When I cleared everything by `em.clear()`?
coubeatczech
@coubeatczech This is an entirely different question that is not easy to discuss in a comment box. Please open another question and mention your JPA provider (but your use case is really weird anyway).
Pascal Thivent