May 10, 2021 Java
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.
Before we do, we need to understand the state of the entity and its transformation, as shown in the figure below
There are four states in the JPA entity lifecycle
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();
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; }
Once the entity is in the database, the next line of code shows how to find it.
Employee emp = em.find(Employee.class, 1);
To remove an entity from the database,
EntityManager
remove
Employee emp = em.find(Employee.class, 1); em.remove(emp);
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");
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();
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.
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(); } }
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.