java - JPA - Batch/Bulk Update - What is the better approach? -


i found jpa not support following update:

update person p set p.name = :name_1 p.id = :id_1,                     p.name = :name_2 p.id = :id_2,                     p.name = :name_3 p.id = :id_3                     ....                   // go on, depending on size of input. in 100s 

so have 2 options:

option 1:

query q = em.createquery("update person p set p.name = :name p.id = :id");  ( int x=0; personslist.length; x++ ) {       // add name , id parameters       em.executeupdate();  } 

questions:

  1. is that's needed batch update? else need add? set hibernate.jdbc.batch_size", "20"
  2. is optimistic lock enabled here default? (i not have @version in entity though)
  3. what need in order enforce optimistic locking, if not @version?

option 2:

construct 1 single query using either select case syntax or criteria api

questions:

  1. does batching still happen here? (in single big query)
  2. is better 1st approach in terms of performance?
  3. whats recommended approach out of these 2 options? other better approach?

if going use batch see this chapter of hibernate documentation

the batch_size more memory optimization query optimization, query remain same, can minimize roundtrip full use of memory. need flush() , clear() each n times depend of setting of batch_size.

but still . .

update in 1 statement faster update in multiple statement, if :

  • can loop , in sql
  • no need cascade update other entities
  • you need faster performance when updating multiple value
  • and no need other hql advantage prepared statement prevent sql injection

then can consider create native query hql.


Comments