JPA and Hibernate - Fetch Data using CriteriaBuilder

package edu.raj.learn;


import java.util.List;


import jakarta.persistence.EntityManager;

import jakarta.persistence.EntityManagerFactory;

import jakarta.persistence.Persistence;

import jakarta.persistence.criteria.CriteriaBuilder;

import jakarta.persistence.criteria.CriteriaQuery;

import jakarta.persistence.criteria.Root;


public class FetchWithCriteria {

public static void main(String[] args) {

        // Create EntityManagerFactory and EntityManager

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-pu");

        EntityManager em = emf.createEntityManager();


        // Start a transaction

        em.getTransaction().begin();


        // Create a CriteriaBuilder and CriteriaQuery

        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<Employee> cq = cb.createQuery(Employee.class);

        Root<Employee> root = cq.from(Employee.class);


        // Create the query to fetch all Employee entities

        cq.select(root);

        List<Employee> employees = em.createQuery(cq).getResultList();


        // Print the list of employees

        for (Employee emp : employees) {

            System.out.println(emp.getName() + " - " + emp.getDepartment());

        }


        // Commit transaction

        em.getTransaction().commit();


        // Close the EntityManager

        em.close();

        emf.close();

    }

}


Comments