updating multiple rows using JPA

akp picture akp · Nov 1, 2010 · Viewed 33.5k times · Source

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.

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · Nov 1, 2010

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.