JPA flush vs commit

前端 未结 3 2072
北海茫月
北海茫月 2020-12-20 17:19

in JPA, if we call EntityTransaction.commit(), does it automatically call EntityManager.flush()? or should we call them both? what is the difference? because i have problem

相关标签:
3条回答
  • 2020-12-20 17:41

    If you have a @Version annotated column in your entity and call entityManager.flush(), then you will either (immediately!) get an OptimisticLockException, or the database will lock this row (or table). In the later case you can still call setRollbackOnly(), and the lock will later be released without a DB change.

    Or from a different perspective, with flush() you can create a (pessimistic) lock on that database row. The others will still see the old entry, but if they try to update they will be blocked, until the lock is released.

    All this is also true for CMT (container managed transactions). Instead of waiting for the moment, where the service method is finished and the CMT commit is performed, you can call flush() (even several times) in your service method and handle the OptimisticLockException(s) immediately.

    0 讨论(0)
  • 2020-12-20 17:49

    em.flush() - It saves the entity immediately to the database with in a transaction to be used further and it can be rolled back.

    em.getTransaction().commit - It marks the end of transaction and saves all the chnages with in the transaction into the database and it can't be rolled back.

    Refer https://prismoskills.appspot.com/lessons/Hibernate/Chapter_14_-_Flush_vs_Commit.jsp

    0 讨论(0)
  • 2020-12-20 17:53

    if we call EntityTransaction.commit(), does it automatically call EntityManager.flush()?

    Yes

    what is the difference?

    In flush() the changes to the data are reflected in database after encountering flush, but it is still in transaction.flush() MUST be enclosed in a transaction context and you don't have to do it explicitly unless needed (in rare cases), when EntityTransaction.commit() does that for you.

    Source

    0 讨论(0)
提交回复
热议问题