1

I'm using the EntityManager to persist data into my database.

public void save(X x){
    entityManager.persist(x);
    entityManager.flush();
    triggerDataChange();
}

After flushing the data I call the triggerDataChange() Method to send a message to an external component which depends on the newly written data.

Question: Can I rely on the flush method returning after the data has been written to database successfully?

Thanks for your help.

herzrasen
  • 377
  • 4
  • 13
  • Yes, flushing commits the changes to the DB. (But it can still be rolled back.) – K.C. Feb 21 '12 at 10:07
  • BTW: if you use hibernate, look at the possible flush modes: http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/FlushMode.html – K.C. Feb 21 '12 at 10:10
  • I think when he says "commits the changes to the DB", he means "doesn't commit the changes to the DB" 8=}. Your other app would have to read uncommitted data from the db, which is not a usual thing to do. Really what you probably want is to commit the data (i.e. finish the transaction) and then call your external system. Otherwise the external system could make a decision based on data that could be rolled back. – davidfrancis Feb 21 '12 at 11:22
  • @davidfrancis Sorry, I don't understand. Maybe it's my English (not a native speaker). I thought that it was as follows: entityManager.flush() : empty the internal SQL instructions cache, and execute it immediately to the database. See: http://stackoverflow.com/questions/4275111/correct-use-of-flush-in-jpa-hibernate – K.C. Feb 21 '12 at 12:33
  • 1
    I would imagine your English is far far better than my pathetic attempts at your native language!! Yes it does depend on your definition of "commit". I personally would avoid using "commit" in database terms unless you are referring to committing a transaction - probably better to say "persist". e.g. flush persists data to the database, but it can still be rolled back. – davidfrancis Feb 21 '12 at 12:59
  • Ah yes, I was trying to say that. Thanks for clarifying. – K.C. Feb 21 '12 at 13:08

1 Answers1

1

Your transaction is same so even if the transaction rolls back it rolls back completely. Flush will not commit the transaction as it can be still rolled back. So In your implementation whatever you are doing is fine.

Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72