JPA Tutorial - JPA EntityManager








We use Entity Manager to persist entities to the database.

Create EntityManager

All entity managers come from factories of type javax.persistence.EntityManagerFactory.

The following example demonstrates creating an EntityManagerFactory for the persistence unit named "EmployeeService":

EntityManagerFactory emf = 
    Persistence.createEntityManagerFactory("EmployeeService");

The following example demonstrates creating an entity manager from the factory acquired in the previous example:

EntityManager em = emf.createEntityManager();




Save Entity

We use the entity manager to persist an instance of Employee.

Employee emp = new Employee(158);
em.persist(emp);

The following code shows how to use EntityManager in a method that creates a new employee and persists it to the database.

public Employee createEmployee(int id, String name, long salary) {
    Employee emp = new Employee(id);
    emp.setName(name);
    emp.setSalary(salary);
    em.persist(emp);
    return emp;
}




Find Entity

Once an entity is in the database, the next line of code shows how to find it.

Employee emp = em.find(Employee.class, 1);

Remove Entity

To delete an entity from database, call the remove method from EntityManager.


Employee emp = em.find(Employee.class, 1);
em.remove(emp);

Update Entity

To update an entity we can just call the setter method on an managed entity. A managed entity is an entity returned from the EntityManager.

Employee emp = em.find(Employee.class, 1);
emp.setName('new Name');

Transactions

The following code shows how to start and commit a transaction.

em.getTransaction().begin(); Employee emp = new Employee(158); em.persist(emp); em.getTransaction().commit();

Queries

In JPA, there is a new a query language called Java Persistence Query Language (JP QL).

The following example shows how to create a dynamic query and then execute it to obtain all the employees in the database.

TypedQuery<Employee> query = 
     em.createQuery("SELECT e FROM Employee e",
                     Employee.class);
List<Employee> emps = query.getResultList();

We create a TypedQuery<Employee> object by issuing the createQuery() call on the EntityManager and passing in the JP QL string.

The JP QL string refers not to an EMPLOYEE database table but to the Employee entity.

Example

The following code shows a simple fully functional class that can be used to issue the typical create, read, update, and delete (CRUD) operations on Employee entities.

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

public class EmployeeService {
  protected EntityManager em;

  public EmployeeService(EntityManager em) {
    this.em = em;
  }

  public Employee createEmployee(int id, String name, long salary) {
    Employee emp = new Employee(id);
    emp.setName(name);
    emp.setSalary(salary);
    em.persist(emp);
    return emp;
  }

  public void removeEmployee(int id) {
    Employee emp = findEmployee(id);
    if (emp != null) {
      em.remove(emp);
    }
  }

  public Employee raiseEmployeeSalary(int id, long raise) {
    Employee emp = em.find(Employee.class, id);
    if (emp != null) {
      emp.setSalary(emp.getSalary() + raise);
    }
    return emp;
  }

  public Employee findEmployee(int id) {
    return em.find(Employee.class, id);
  }

  public List<Employee> findAllEmployees() {
    TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e",
        Employee.class);
    return query.getResultList();
  }
}

Main Class


import java.util.List;

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

public class Main {

  public static void main(String[] args) {
    EntityManagerFactory emf = Persistence
        .createEntityManagerFactory("EmployeeService");
    EntityManager em = emf.createEntityManager();
    EmployeeService service = new EmployeeService(em);

    em.getTransaction().begin();
    Employee emp = service.createEmployee(1, "Tom", 5000);
    em.getTransaction().commit();
    System.out.println("Persisted " + emp);

    emp = service.findEmployee(1);
    System.out.println("Found " + emp);

    List<Employee> emps = service.findAllEmployees();
    for (Employee e : emps)
      System.out.println("Found employee: " + e);

    em.getTransaction().begin();
    emp = service.raiseEmployeeSalary(1, 1000);
    em.getTransaction().commit();
    System.out.println("Updated " + emp);

    em.getTransaction().begin();
    service.removeEmployee(158);
    em.getTransaction().commit();
    System.out.println("Removed Employee 158");

    em.close();
    emf.close();
  }
}

Persistence Unit

The configuration that describes the persistence unit is defined in an XML file called persistence.xml.

Each persistence unit is named. A single persistence.xml file can contain one or more named persistence unit configurations.

The following code shows a demo for a persistence.xml File

<persistence>
   <persistence-unit name="EmployeeService" transaction-type="RESOURCE_LOCAL">
      <properties>
         <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
         <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/EmpServDB;create=true"/>
         <property name="javax.persistence.jdbc.user" value="APP"/>
         <property name="javax.persistence.jdbc.password" value="APP"/>
      </properties>
   </persistence-unit>
</persistence>

persistence.xml file should be placed in the META-INF directory.