In this article, we will discuss various ways to update JPA entity objects into a database.
Modifying existing entity objects that are stored in the database is based on transparent persistence, which means that changes are detected and handled automatically.
Learn complete JPA at JPA Tutorial - Java Persistence API
Learn Hibernate ORM Framework at Hibernate Tutorial
This article covers the following topics:
- Transparent Update
- UPDATE Queries
1. Transparent Update
Once an entity object is retrieved from the database (no matter which way) it can simply be modified in memory from inside an active transaction. In this example, we use a Student JPA entity to perform an update database operation.
public void updateEntity() {
EntityManager entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
entityManager.getTransaction().begin();
Student student = entityManager.find(Student.class, 1);
System.out.println("student id :: " + student.getId());
System.out.println("student firstname :: " + student.getFirstName());
System.out.println("student lastname :: " + student.getLastName());
System.out.println("student email :: " + student.getEmail());
// The entity object is physically updated in the database when the transaction
// is committed
student.setFirstName("Ram");
student.setLastName("jadhav");
entityManager.getTransaction().commit();
entityManager.close();
}
Refer JPA CRUD Example article for a complete example.
The entity object is physically updated in the database when the transaction is committed. If the transaction is rolled back and not committed the update is discarded.
2. UPDATE Queries
UPDATE queries provide an alternative way for updating entity objects in the database. Modifying objects using an UPDATE query may be useful especially when many entity objects have to be modified in one operation.
public void updateEntity() {
EntityManager entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
entityManager.getTransaction().begin();
Query query = entityManager
.createQuery("UPDATE Student e SET e.firstName = 'Ram' WHERE e.id = :id");
query.setParameter("id", 1);
int rowsUpdated = query.executeUpdate();
System.out.println("entities Updated: " + rowsUpdated);
entityManager.getTransaction().commit();
entityManager.close();
}
On success - the executeUpdate method returns the number of objects that have been modified by the query.
Refer complete JPA CRUD operations example at JPA CRUD Example
Learn complete JPA at JPA Tutorial - Java Persistence API
Learn Hibernate ORM Framework at Hibernate Tutorial
Comments
Post a Comment
Leave Comment