I want to update all fields of a table that has value of colum NAME as 'PCNAME'. The table name which i want to update is XYZ.I want to update only some fields and not keep some unchanged.
This will affect many rows and not a single row as there will be many rows with NAME='PCNAME' How can i do it using JPA.I have entity class associated with this table.
CrudRepository save() to Add a New Instance Notice that we never specified an id. The instance is initially created with a null value for its id, and when we call the save() method, an id is automatically generated. The save() method returns the saved entity, including the updated id field.
The Java Persistence API (JPA) is a specification that defines how to persist data in Java applications. The primary focus of JPA is the ORM layer. Hibernate is one of the most popular Java ORM frameworks in use today.
You can either do it the object oriented way or using an update query.
Object oriented:
public void setNameOfAllEntities(String newname){
List<MyEntity> items =
entityManager.createQuery("from MyEntity", MyEntity.class)
.getResultList();
for(MyEntity entity : items){
entity.setName(newname);
}
}
With Update Query (untested):
public void setNameOfAllEntities(final String newname){
final int changes =
entityManager.createQuery("update MyEntity set name = :name")
.setParameter("name", newname)
.executeUpdate();
System.out.println(changes + " rows changed");
}
Obviously, the second version performs better.
seanizer's answer is correct (+1) and a bulk update would be indeed nice for this use case. But you must take some precautions with bulk update operations. To paraphrase the JPA specification:
My suggestion would thus be to at least increment the version column to avoid concurrency problem with other threads:
UPDATE XYZ xyz
SET xyz.name = :newname, xyz.version = xyz.version + 1
And to perform it in a separate transaction or before loading any XYZ as previously explained.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With