
JPA - Persistence Operations
- JPA - Entity Managers
- JPA - Create Employee Example
- JPA - Update Employee Example
- JPA - Find Employee Example
- JPA - Delete Employee Example
- JPA - Criteria API
JPA - JPQL
- JPA - JPQL
- JPA - Scalar Function
- JPA - Aggregate Function
- JPA - Between Keyword
- JPA - Like Keyword
- JPA - Order By Clause
- JPA - Named Query
JPA - Advanced Mappings
- JPA - Advanced Mappings
- JPA - Single Table Strategy
- JPA - Joined Table Strategy
- JPA - Table per Class Strategy
JPA - Entity Relationships
- JPA - Entity Relationships
- JPA - @ManyToOne Relationships
- JPA - @OneToMany Relationships
- JPA - @OneToOne Relationships
- JPA - @ManyToMany Relationships
JPA - Useful Resources
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.