Java Persistence API – EntityManager

JPA is annotation based OR mapping. It is very powerful as the annotation binds a datastore to JAVA classes. These objects are datastore context aware. The JPA library manages the write/update to the objects.

The EntityManager class has many methods. There are two methods that concerns most of datastore operations and their usage are:

merge() – does a select to check if the entity exists so that it can do update. Any detached JPA entity must be merged. If persist() is used instead, then a new entity is created in the store.

persist() – deos not do select and does insert with generated ID. This is for persisting new object into a datastore.

Persistence Unit

In an application, persistable objects can be independently grouped so that they can be treated separately. They may be grouped within a different DAO object. JPA introduces the idea of a persistence-unit. A persistence-unit provides a convenient way of specifying a set of metadata files, and classes, and jars that contain all classes to be persisted in a grouping. The persistence-unit is named, and the name is used for identifying it.

Persistence Unit should be used so that a group of classes may be stored in different stores. This is very powerful way of designing an application that has lets say, structured (SQL), or documents (NoSQL) based data stores.

Reference