JPA - Update Employee Example



This chapter takes you through simple example with JPA to update 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 update an employee in the database.

Update Employee

To Update an employee, we need to get record form database, make changes, and finally commit it. The class named UpdateEmployee.java is shown as follows:

UpdateEmployee.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 UpdateEmployee {
   public static void main( String[ ] args ) {
      EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "Eclipselink_JPA" );
      
      EntityManager entitymanager = emfactory.createEntityManager( );
      entitymanager.getTransaction( ).begin( );
      Employee employee = entitymanager.find( Employee.class, 1201 );
      
      //before update
      System.out.println( employee );
      employee.setSalary( 46000 );
      entitymanager.getTransaction( ).commit( );
      
      //after update
      System.out.println( employee );
      entitymanager.close();
      emfactory.close();
   }
}

Output

After compilation and execution of the above program you will get notifications from Eclipselink library on the console panel of eclipse IDE.

For result, open the MySQL workbench and type the following queries.

use jpadb
select * from employee

The effected database table named employee will be shown in a tabular format as follows:

Eid Ename Salary Deg
1201 Gopal 46000 Technical Manager

The salary of employee, 1201 is updated to 46000.

Advertisements