Monday, December 28, 2015

Persistence Context

Java Persistence API uses javax.persistence.EntityManager to manage Entity instances and their life cycle(and hibernate does it using org.hibernate.Session). Each EntityManager instance is associated with a Persistence Context. 

EntityManager begines a new Persistence Context with each transaction and once the transaction ends (with commit or rollback) Context also ends. Within the transaction, entities retrieved from DB are managed entities (or instances which get saved become managed as well). When transaction completes, all entities loose their association from context and become detached.  

So, Persistence Context is cache of managed entity instances attached with your unit of work (or transaction). We don't need to do anything to enable it, it's always there (and we can't turn it off)! This Context has scope of a unit of work and it gets processed in a single thread (so it doesn't have issues like lock management or concurrent access).




How does it help

  • If we ask to load an entity using a primary key, EntityManager/Session checks first in the Context- If the entity is found there, there will be no DB hit. It's repeatable read for the application. So we get repeatable read absolutely free!
  • At most single object (entity) can represent any database row; there is no conflict. And all changes made to that row can be safely written back. 
  • Changes made to a managed entity is immediately visible to other (managed) entities in the context. 
  • At the end of transaction, JPA providers like Hibernate scans persistence context to find out which all entities got modified and only entities with any modification (or dirty attribute) gets propagated to the database. This is known as automatic-dirty-checking

Final Note

Persistence Context hold a copy/snapshot of each persistence object. The snapshot is used by JPA provider to do dirty checking (detect any modification done to the object). So if you carelessly load large number of objects you might run out of memory (OutOfMemoryException).  So be mindful of the impact on memory when you load records from DB (put proper condition in queries to avoid un-necessary load). 


References
https://docs.jboss.org/hibernate/orm/4.0/devguide/en-US/html/ch03.html

No comments:

Post a Comment