JPA - Find Employee Example



This chapter takes you through simple example with JPA to search an Employee record in the MySQL database. We've created Employee.java as entity and persistence.xml in Entity Managers chapter.

Now let's create a service to find an employee in the database.

Example - Find Employee

To Find an employee we will get record from database and display it. In this operation, EntityTransaction is not involved any transaction is not applied while retrieving a record.

The class named FindEmployee.java as follows.

FindEmployee.java

package com.tutorialspoint.eclipselink.service;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;
import com.tutorialspoint.eclipselink.entity.Employee;

public class FindEmployee {
   public static void main( String[ ] args ) {
   
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      EntityManager entitymanager = emfactory.createEntityManager();
      Employee employee = entitymanager.find( Employee.class, 1201 );

      System.out.println("employee ID = " + employee.getEid( ));
      System.out.println("employee NAME = " + employee.getEname( ));
      System.out.println("employee SALARY = " + employee.getSalary( ));
      System.out.println("employee DESIGNATION = " + employee.getDeg( ));
   }
}

Output

After compilation and execution of the above program you will get output from Eclipselink library on the console panel of eclipse IDE as follows:

employee ID = 1201
employee NAME = Gopal
employee SALARY = 46000.0
employee DESIGNATION = Technical Manager
Advertisements