ziMtyth
ziMtyth

Reputation: 1048

Understanding a passage in `Pro JPA 2 Mastering the java Persistence API`?

I am new to JPA, I am reading Pro JPA 2 Mastering the java Persistence API and I have read the following passage:

a flush of the persistence context could occur at any time if the persistence provider deems it necessary.

My questions

I want to understand the meaning in detail of this sentence deems it necessary. Any help is welcomed, thanks in advance.

Upvotes: 0

Views: 71

Answers (1)

One such scenario is as per JPA 2.1 Specification - Section 3.10.8 Queries and Flush Mode - The persistence provider is responsible for ensuring that all updates to the state of all entities in the persistence context which could potentially affect the result of the query are visible to the processing of the query.

Although it is implementation dependent, but you can notice below behavior with hibernate as persistence provider deciding to flush before firing an HQL as the state in the persistence context could affect the query result.

So with Hibernate as persistence provider,

  1. Open an entityManager.
  2. Create new Employee entity and call persist method on it.
  3. It may not result in an immediate insert statement because session acts as a transactional-write behind cache and tries to defer flushing up until last moment possible.
  4. Fire a JPQL to get the count of employees using the entityManager.
  5. At this point, you would see an insert statement is fired to persist the newly created employee before firing the select count(*) from employee JPQL.

So in this case it has decided to flush the state because the insertion of employee object could affect the result of JPQL query.

Upvotes: 1

Related Questions