Can I update multiple columns of table by query language using JPA

java, jpa

Solution

Since you are creating a standalone application, you must open a transaction first, then you can simply change the field values in your object and when the transaction is committed, the changes get flushed to the database automatically.

EntityTransaction tx = entityManager.getTransaction();
try {
   tx.begin();
   try {
      for(SimpleTable simpleTable : simpleTables){
         simplaTable.setAddress(newAddress);
      }
   } finally {
      tx.commit();
   }
} catch (Exception e) {
   // handle exceptions from transaction methods
}

--Edit--

An alternative to edit all records without having to first fetch them is to do a bulk update, still within a transaction, like this:

entityManager.createQuery("UPDATE SimpleTable s " +
               "SET s.address.state = ?1 " +
               "WHERE s.address.country = ?2")
  .setParameter(1, "FL")
  .setParameter(2, "US")
  .executeUpdate();

Problem

I created one table like student and I fetched the address based on age (like age = 22). Now I want to update the address based on age "22" to all address columns of table. How can I do this? Below is my code: ``` public static void main(String[] args) { EntityManager entityManager = Persistence.createEntityManagerFactory( "demoJPA").createEntityManager(); Query query = entityManager.createQuery("SELECT student FROM Student student WHERE student.age = 22"); System.out.println("Data is" + query.getResultList().size()); List<Simpletable> simpletable = query.getResultList(); for (Simpletable simpletable1 : simpletable){ System.out.println(simpletable1.getAddress()); } } ``` I fetched data but how can I update now. Is it possible to iterate through a loop and setAddress("US")

Original source