Java Pesistence API Notes


JPA

As you create Session from a SessionFactory, it’s not hard to understand that you use EntityManagerFactory to create an instance of EntityManager. However, because JPA is a standard applicable to Enterprise and Standalone applications, there are a couple of modes for obtaining or creating the EntityManagerFactory itself—one that will be created in a managed environment such as Application Servers or Web containers while the other in a standalone application.

Once you have the EntityManager (obtained from EntityManagerFactory), the next step is to declare a persistence unit. A persistence unit is a logical group of persistent classes (called entities in JPA lingo), database settings, and relational mappings.

The JPA specification classifies two types of entity managers: one that runs in a con- tainer-managed environment, and another that runs in a standalone JVM. The former one is typically a Java Enterprise Edition (JEE) container such as an application server or a web container, while the latter is a Java Standard Edition standalone program.

The EntityManager itself is no different in both types but the EntityManagerFactory that creates the EntityManager is a bit unique in how it is configured and created.

In a standalone environment, you should create the EntityManager as shown here:

private EntityManagerFactory factory = null; 
private EntityManager entityManager = null; ..
private void init() {
factory = Persistence.createEntityManagerFactory("trade-mysql-pu");
entityManager = factory.createEntityManager();
}

You should pass in the name of the previously defined persistence unit (from persistence.xml) to the createEntityManagerFactory() method. We then obtain the EntityManager by calling createEntityManager on the factory.

Java  JPA