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
- http://stackoverflow.com/questions/1069992/jpa-entitymanager-why-use-persist-over-merge
- https://cloud.google.com/appengine/docs/java/datastore/jpa/overview
- http://www.datanucleus.org/products/datanucleus/jpa/persistence_unit.html
- http://docs.oracle.com/javaee/7/api/javax/persistence/Persistence.html#createEntityManagerFactory(java.lang.String)