JPA and Hibernate - Fetch By Id

 package edu.raj.learn;


import jakarta.persistence.EntityManager;

import jakarta.persistence.EntityManagerFactory;

import jakarta.persistence.Persistence;


public class FindById {

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();


// Fetch the Employee entity that you want to update

Employee emp = em.find(Employee.class, 2); // Assuming the employee ID is 1


System.out.println(emp.getDepartment());


// Commit transaction to persist changes

em.getTransaction().commit();


// Close the EntityManager

em.close();

emf.close();

}

}

Comments