In Java Persistence API (JPA), the EntityManager
is the primary interface for interacting with the persistence context. JPQL (Java Persistence Query Language) is used to query entities using object-oriented syntax rather than SQL. This article explains these concepts with examples.
The EntityManager
interface provides methods to manage entity lifecycle and perform database operations. Some key methods include:
persist(Object entity)
- Saves an entity to the database.merge(Object entity)
- Updates an existing entity or saves a new one.remove(Object entity)
- Deletes an entity.find(Class entityClass, Object primaryKey)
- Fetches an entity by its primary key.createQuery(String jpql)
- Executes JPQL queries.
First, set up the persistence.xml
file:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1"> <persistence-unit name="examplePU"> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_example"/> <property name="javax.persistence.jdbc.user" value="root"/> <property name="javax.persistence.jdbc.password" value="password"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="hibernate.show_sql" value="true"/> </properties> </persistence-unit> </persistence>
Define an entity class:
import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private double price; // Getters and setters public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }
Using EntityManager
to persist data:
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class MainApp { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("examplePU"); EntityManager em = emf.createEntityManager(); Product product = new Product(); product.setName("Smartphone"); product.setPrice(699.99); em.getTransaction().begin(); em.persist(product); em.getTransaction().commit(); em.close(); emf.close(); System.out.println("Product saved successfully!"); } }
JPQL (Java Persistence Query Language) is a query language for entities. Unlike SQL, it uses entity names and field names instead of table and column names. JPQL can be used for retrieval, updates, and deletions.
JPQL syntax:
SELECT e FROM EntityName e
- Fetch all records of an entity.WHERE
- Filter results based on conditions.ORDER BY
- Sort results.import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; import java.util.List; public class JPQLExample { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("examplePU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); // JPQL query Query query = em.createQuery("SELECT p FROM Product p WHERE p.price > :minPrice"); query.setParameter("minPrice", 500.00); List<Product> products = query.getResultList(); for (Product product : products) { System.out.println(product.getName() + " - " + product.getPrice()); } em.getTransaction().commit(); em.close(); emf.close(); } }
em.getTransaction().begin(); Query updateQuery = em.createQuery("UPDATE Product p SET p.price = :newPrice WHERE p.name = :name"); updateQuery.setParameter("newPrice", 799.99); updateQuery.setParameter("name", "Smartphone"); int rowsUpdated = updateQuery.executeUpdate(); em.getTransaction().commit(); System.out.println("Rows updated: " + rowsUpdated);
em.getTransaction().begin(); Query deleteQuery = em.createQuery("DELETE FROM Product p WHERE p.name = :name"); deleteQuery.setParameter("name", "Smartphone"); int rowsDeleted = deleteQuery.executeUpdate(); em.getTransaction().commit(); System.out.println("Rows deleted: " + rowsDeleted);
Named queries are predefined JPQL queries with fixed syntax. They are defined using the @NamedQuery
annotation.
@Entity @NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p") public class Product { // Fields, getters, and setters } // Using NamedQuery Query namedQuery = em.createNamedQuery("Product.findAll"); List<Product> products = namedQuery.getResultList();
The EntityManager
interface and JPQL are core components of JPA, enabling developers to interact with databases using object-oriented concepts. Understanding their usage helps create efficient and maintainable data-driven applications.