How do I write a simple JPQL query using Hibernate?

To write a simple JPQL (Java Persistence Query Language) query using Hibernate, follow these steps:

Example: Basic JPQL Query

For example, consider we have an entity: Employee

package org.kodejava.hibernate;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee {
    @Id
    private Long id;
    private String name;
    private String department;
    private Double salary;

    // Getters and setters
}

1. Write the JPQL Query

A JPQL query allows you to query entities in an object-oriented way. For instance, fetching employees with a salary greater than 50000:

String jpqlQuery = "SELECT e FROM Employee e WHERE e.salary > :salary";

2. Using EntityManager to Execute the Query

You need to use the EntityManager to create and execute a JPQL query. Here is how you can do it:

package org.kodejava.hibernate;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import jakarta.persistence.TypedQuery;
import java.util.List;

public class JPQLExample {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence-unit-name");
        EntityManager em = emf.createEntityManager();

        try {
            em.getTransaction().begin();

            // JPQL query
            String jpqlQuery = "SELECT e FROM Employee e WHERE e.salary > :salary";

            // TypedQuery to avoid type casting
            TypedQuery<Employee> query = em.createQuery(jpqlQuery, Employee.class);
            query.setParameter("salary", 50000.0);

            // Executing the query and fetching the results
            List<Employee> employees = query.getResultList();

            // Display the result
            for (Employee employee : employees) {
                System.out.println("Employee: " + employee.getName() + ", Salary: " + employee.getSalary());
            }

            em.getTransaction().commit();
        } finally {
            em.close();
            emf.close();
        }
    }
}

Explanation of the Code

  1. JPQL Query:
    • "SELECT e FROM Employee e WHERE e.salary > :salary" is the JPQL query.
    • e is an alias for the entity. Employee
    • :salary is a named parameter.
  2. EntityManager:
    • The EntityManager is used to create queries and execute them.
    • The createQuery() method takes the JPQL query string and the result type.
  3. TypedQuery:
    • A TypedQuery is preferred for type safety and avoids casting the result.
  4. Parameter Binding:
    • setParameter() binds the value to the named parameter in the JPQL query.
  5. Fetching Results:
    • getResultList() fetches the results as a list of entities matching the query condition.

Additional Notes

  • JPQL uses the entity and its fields, not the database table or column names.
  • Make sure your is correctly configured with the persistence unit name. persistence.xml

This is how you write and execute a simple JPQL query with Hibernate.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.