Find by class in JPA
This is an example of how to find an object by class in JPA. The Java Persistence API provides Java developers with an object/relational mapping facility for managing relational data in Java applications.
Here, we are using JPA to retrieve an object by class, as shown below:
The FindByClassInJPA class
In FindByClassInJPA
we create an EntityManagerFactory
interface to interact with the entity manager factory for MyPeristenceUnit
, that is defined in persistence.xml
file. We create an EntityManager, using the createEntityManager()
API method. Then, we create new Employee
objects. The new objects are written to the database, using the persist(java.lang.Object entity)
API method of EntityManager
. The getTransaction().begin()
and getTransaction().commit()
methods are used before and after the EntityManager
invokes a method so that a transaction begins and ends. Employee
objects can be retrieved, using the createQuery(String qlString)
API method of EntityManager, with an sql String query. Then, using the getResultList()
of Query to execute a SELECT query that returns all results in a list that is cast to a list of Employee
objects.
package com.javacodegeeks.snippets.enterprise; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; public class FindByClassInJPA { @SuppressWarnings("unchecked") public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyPersistenceUnit"); EntityManager em = emf.createEntityManager(); // create the employees em.getTransaction().begin(); for (int i = 0; i < 5; i++) { Employee employee = new Employee(); employee.setName("employe_"+i); employee.setSurname("surname_"+i); employee.setTitle("Engineer_"+i); employee.setCreated(new Date()); em.persist(employee); } em.getTransaction().commit(); // retrieve the employees em.getTransaction().begin(); Query query = em.createQuery("SELECT e FROM Employee e"); List<Employee> employees = (List<Employee>) query.getResultList(); if (employees!=null && employees.size()>0) { for (Employee employee : employees) { System.out.println(employee); } } em.getTransaction().commit(); em.close(); emf.close(); } }
Employee Class
The Employee
class is an entity class, annotated with the javax.persistence.Entity
annotation. It uses the @Id
annotation to define its id property, and the @GeneratedValue
annotation with strategy set to GenerationType.AUTO
so that the id gets auto-generated values.
package com.javacodegeeks.snippets.enterprise; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Employee { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String name; private String surname; private String title; private Date created; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } @Override public String toString() { return "Employee [id=" + id + ", name=" + name + ", surname=" + surname + ", title=" + title + "]"; } }
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="MyPersistenceUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" /> <property name="hibernate.hbm2ddl.auto" value="update" /> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.username" value="jcg" /> <property name="hibernate.connection.password" value="jcg" /> <property name="hibernate.connection.url" value="jdbc:mysql://localhost/companydb" /> </properties> </persistence-unit> </persistence>
Output:
Employee [id=1, name=employe_0, surname=surname_0, title=Engineer_0]
Employee [id=2, name=employe_1, surname=surname_1, title=Engineer_1]
Employee [id=3, name=employe_2, surname=surname_2, title=Engineer_2]
Employee [id=4, name=employe_3, surname=surname_3, title=Engineer_3]
Employee [id=5, name=employe_4, surname=surname_4, title=Engineer_4]
This was an example of how to find an object by class in JPA.