Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JPA entity manager


May 10, 2021 Java


Table of contents


An overview of the entity manager

The Entity Manager is used for entities in a management system, it is a bridge between an entity and a database, and by calling the entity manager's methods, you can persist the entities into the database, and you can also package the records in the database into entity objects.

The four states of the entity

Before we do, we need to understand the state of the entity and its transformation, as shown in the figure below

JPA entity manager

There are four states in the JPA entity lifecycle

  • New state: The object is temporary until it is saved into the database. T here is no information about the object in the database, and the object's ID properties are empty. If it is not persisted, object information in a temporary state is lost when the program exits.
  • Managed: An object is persisted after it is saved into or loaded from the database, and does not break away from Session. A t this time there is object information in the database, change the object's id to the primary key value of the corresponding record in the database. Because it's still in Session, persistent objects can do anything about the database, such as getting values for collection properties, and so on.
  • Datached: It is the object that was once persistent, but is now out of Session. A lthough the object in the detached state has an id value and a corresponding database record, it is no longer possible to perform operations on the database. For example, reading a collection property that is delayed loading might throw a lazy load exception.
  • Delete State: Deleted object, with id value, is not yet associated with Persistence Context, but is ready to be deleted from the database.

Create an entity manager

All entity managers come from javax.persistence.EntityManagerFactory

The following example demonstrates creating an EntityManagerFactory

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

The following example shows how to create an entity manager in a factory obtained in the previous example:

EntityManager em = emf.createEntityManager();

Save the entity

We use the entity manager to persist instances of Employee

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

The following code shows how to use EntityManager in methods that create new employees and keep them in 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 the entity

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

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

Delete the entity

To remove an entity from the database, EntityManager remove

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

Update the entity

To update the entity, we can call the setter method on setter management. T he entity in charge EntityManager

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

Transaction

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();

Inquire

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

The following example shows how to create a dynamic query and then execute it to get all 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 making a createQuery() call on EntityManager and passing in the JP QL string.

The JP QL string does not EMPLOYEE the EMPLOYEE database table, but to the Employee entity.

Example

The following code shows a simple, fully functional class that can be used Employee read, update, and delete (CRUD) operations to 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();
  }
}

The 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 called persistence and configuration.

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

The following code shows a .xml the persistence 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.