Make delicious recipes!


JPA's EntityManager


JPA stands for Java Persistence API and it is a standard for ORMs like Hibernate, EJB and Eclipse TopLink.
JPA recommends the use of EntityManagerFactory and EntityManager.
SessionFactory and Session are hibernate-specific, although under the hood, EntityManager calls the hibernate session only.
But if you use EntityManager, then it becomes easy to switch between JPA compliant ORMs.
In case Hibernate Session specific features are needed, it is easier to get the same using:

Session session = entityManager.unwrap(Session.class);
     /************ OR ************/
Session session = (Session) entityManager.getDelegate();



The previous Hibernate Hierarchical Example needs only small changes to make it JPA compliant.
Here is the directory structure for the same.
./src/main/java/com/prismoskills/hibernate/hierarchy/PersistenceExample.java
./src/main/java/com/prismoskills/hibernate/hierarchy/pojos/Address.java
./src/main/java/com/prismoskills/hibernate/hierarchy/pojos/Country.java
./src/main/java/com/prismoskills/hibernate/hierarchy/pojos/Person.java
./src/main/resources/log4j.properties
./src/main/resources/META-INF/persistence.xml
./pom.xml
Note: Two files have been added to our previous example.
One file that has gone missing is ./src/main/resources/hibernate.cfg.xml.
This is no longer required because ./src/main/resources/META-INF/persistence.xml takes its place in JPA.
Contents of changed files are listed below.


Files changed since previous example



src/main/resources/META-INF/persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
        version="2.0">
        
    <persistence-unit name="com.prismoskills.hibernate">
      <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
      
      <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
        <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@//localhost:1522/XE"/>
        <property name="javax.persistence.jdbc.user" value="system"/>
        <property name="javax.persistence.jdbc.password" value="password"/>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.format_sql" value="true"/>
      </properties>
    </persistence-unit>
</persistence>




src/main/resources/log4j.properties
# Root logger option
log4j.rootLogger= INFO , stdout
 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout



pom.xml: hibernate-entitymanager dependency needs to be added for JPA compliance.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.prismoskills.hibernate</groupId>
  <artifactId>persistence</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>persistence</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>4.3.0.CR2</version>
    </dependency>
            
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0</version>
    </dependency>
    
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>
            
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
      <version>4.3.0.CR2</version>
    </dependency>
            
  </dependencies>

 
  <build>
    <plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.1</version>
        <configuration>
            <transformers>
                <transformer
                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                    <manifestEntries>
                        <Main-Class>com.prismoskills.hibernate.hierarchy.PersistenceExample</Main-Class>
                    </manifestEntries>
                </transformer>
            </transformers>
        </configuration>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>shade</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    </plugins>
  </build>
  
</project>




PersistenceExample: This is the class having main().
Here we replace hibernate Session methods with JPA's EntityManager methods.
package com.prismoskills.hibernate.hierarchy;

import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.hibernate.HibernateException;

import com.prismoskills.hibernate.hierarchy.pojos.Address;
import com.prismoskills.hibernate.hierarchy.pojos.Country;
import com.prismoskills.hibernate.hierarchy.pojos.Person;

public class PersistenceExample
{
    static EntityManager em;
    Country country = new Country("USA");
    Address address = new Address("Los Angeles", "California", country, 12345);


    public static void main(String[] args)
    {
        try
        {
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.prismoskills.hibernate");
            em = emf.createEntityManager();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.exit(1);
        }
        PersistenceExample example = new PersistenceExample();

        /* Add some records to the database */
        Integer id1 = example.addRecord("Johny", "Travol", 10);
        Integer id2 = example.addRecord("Bruce", "Almighty", 20);

        /* Update a record */
        example.updateRecord(id1, 50);

        /* Delete */
        example.deleteRecord(id2);

        /* List the records */
        example.listRecords();

        em.close();
        System.out.println("Done with execution");
    }


    /* CREATE a record in the database */
    public Integer addRecord(String fname, String lname, int salary)
    {
        printOperation("Adding Record");
        EntityTransaction tx = null;
        Integer id = null;
        try
        {
            tx = em.getTransaction();
            tx.begin();
            Person p = new Person(fname, lname, salary, address);
            em.persist(p);
            tx.commit();
        }
        catch (Exception e)
        {
            if (tx!=null) tx.rollback();
            e.printStackTrace();
        }
        return id;
    }


    /* READ all the records */
    public void listRecords()
    {
        printOperation("Reading Records");
        try
        {
            List ppl = em.createQuery("FROM Person").getResultList();
            Iterator itr = ppl.iterator();
            while (itr.hasNext())
            {
                Person p = (Person) itr.next();
                System.out.println (
                        "Id: " + p.getPersonId()
                        + ", Name: " + p.getFirstName() + " " + p.getLastName()
                        + ", Salary: " + p.getSalary()
                        );
            }
            System.out.println("\nRead all records.");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    /* UPDATE a column in the DB */
    public void updateRecord(Integer id, int salary )
    {
        printOperation("Updating Record with id = " + id);
        if (id == null)
            return;

        EntityTransaction tx = null;
        try
        {
            tx = em.getTransaction();
            Person p = em.find(Person.class, id);
            p.setSalary( salary );
            em.persist(p);
            tx.commit();
        }
        catch (Exception e)
        {
            if (tx!=null) tx.rollback();
            e.printStackTrace();
        }
    }


    /* Method to DELETE from the records */
    public void deleteRecord(Integer id)
    {
        printOperation("Deleting Record with id = " + id);
        if (id == null)
            return;

        EntityTransaction tx = null;
        try
        {
            tx = em.getTransaction();
            Person p = em.find(Person.class, id);
            em.remove(p);
            tx.commit();
        }
        catch (HibernateException e)
        {
            if (tx!=null)
                tx.rollback();
            e.printStackTrace();
        }
    }

    private void printOperation(String msg)
    {
        System.out.println("\n============= " + msg + " =============");
    }
}



POJO objects and the output remains the same as in previous example.





Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal