What is Persistence Context?

Amrit picture Amrit · Nov 12, 2013 · Viewed 105.8k times · Source

I am new to the Java world and JPA. I was studying JPA and came across many new terms like Entity, persistence. While reading, I could not understand the exact definition for Persistence Context.

Can anyone explain it in simple laymen terms? What is it to do with the data used in the @Entity?

For example, I find this definition too complicated to understand:

A persistence context is a set of entities such that for any persistent identity there is a unique entity instance.

Answer

JamesB picture JamesB · Nov 12, 2013

A persistence context handles a set of entities which hold data to be persisted in some persistence store (e.g. a database). In particular, the context is aware of the different states an entity can have (e.g. managed, detached) in relation to both the context and the underlying persistence store.

Although Hibernate-related (a JPA provider), I think these links are useful:

http://docs.jboss.org/hibernate/core/4.0/devguide/en-US/html/ch03.html

http://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/architecture.html

In Java EE, a persistence context is normally accessed via an EntityManager.

http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManager.html

The various states an entity can have and the transitions between these are described below:

http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/objectstate.html

http://gerrydevstory.com/wp-content/uploads/2012/05/jpa-state-transtition.png