Updating an Entity :
- Once an entity in the database,
Student student = entintyManager.find(Student.class, 1L);
this line will retrieve student entity where identifier value is 1. - The above line makes the state of Student object “persistent”.
- Persistent state instances are always associated with persistence-context and transnational.
- If we are changing persistent State object values those are synchronized automatically with the database while committing the transaction.
Note:
To understand JPA entity life cycle completely see this tutorial JPA Entity lifecycle
Persistence transition or state change when EntityManager’s find() called :
Technologies Used in all of examples :
- JPA 2.1
- Hibernate 5.2.6
- MySql 8.0
- Maven 3
- Spring Tool Suite (STS) 3.9.8
- Java 1.8
Mapping Studen.java class
@Entity(name="STUDENT") public class Student { @Id @GeneratedValue(strategy=GenerationType.AUTO, generator="native") @GenericGenerator(name = "native", strategy = "native") @Column(name = "ID") private Long studentId; @Column(name = "FNAME") private String firstName; @Column(name = "LNAME") private String lastName; @Column(name = "CONTACT_NO") private String contactNo; // setters and getters
Updating Entity Code :
Following example demonstrates updating column value of Student table when a Student record already exist in DB.
public static void main( String[] args ) { EntityManagerFactory emf = null; EntityManager entityManager = null; EntityTransaction transaction = null; try{ emf = Persistence.createEntityManagerFactory("jbd-pu"); entityManager = emf.createEntityManager(); transaction = entityManager.getTransaction(); transaction.begin(); /* When ever EntityManager's find() calls the state of Student instance will be "Persistent" */ Student student = entityManager.find(Student.class, 2L); /*If we are changing persistent State object values, * those are synchronized automatically with the database while committing the transaction.*/ student.setFirstName("Peter"); transaction.commit(); }catch(Exception e){ transaction.rollback(); }finally{ entityManager.close(); emf.close(); } }
Output :
INFO - HHH000397: Using ASTQueryTranslatorFactory Hibernate: select student0_.ID as ID1_0_0_, student0_.CONTACT_NO as CONTACT_2_0_0_, student0_.FNAME as FNAME3_0_0_, student0_.LNAME as LNAME4_0_0_ from STUDENT student0_ where student0_.ID=? Hibernate: update STUDENT set CONTACT_NO=?, FNAME=?, LNAME=? where ID=? INFO - HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/jpa_JBD]
To update detached entities to the database, use merge method.
Download Application – JPA-Entity-Update.zip (10 KB)