Update multiple rows using hibernate criteria

I am trying to run an update request that will look like this: sql:

update studentMaster set sess_status = 'G' where ACADEM_YEAR = COURSE_YEAR; 

I am trying to recreate a query using Criteria as follows:

 public void updateSessionStatus() { Session sess = factory.openSession(); Transaction tx = null; try { tx = sess.beginTransaction(); Criteria crit = sess.createCriteria(CollegeStudentsMaster.class); crit.add(Restrictions.eqProperty("academicYear", "courseYears")); CollegeStudentsMaster e = (CollegeStudentsMaster) crit.uniqueResult(); e.setSessionStatus("G"); sess.saveOrUpdate(e); tx.commit(); } catch (HibernateException asd) { if (tx != null) { tx.rollback(); } log.debug(asd.getMessage()); } finally { sess.close(); } } 

This does not work, because there are many lines that satisfy these criteria, my unique result is the problem here, I think. How can I convert this to an update for all rows that match the criteria. I don’t want to use the HQL query, I rather do it using criteria.

+7
java hibernate persistence
source share
1 answer
 public void updateSessionStatus() { Session sess = factory.openSession(); Transaction tx = null; try { tx = sess.beginTransaction(); Criteria crit = sess.createCriteria(CollegeStudentsMaster.class); crit.add(Restrictions.eqProperty("academicYear", "courseYears")); // Here is updated code ScrollableResults items = crit.scroll(); int count=0; while ( items.next() ) { CollegeStudentsMaster e = (CollegeStudentsMaster)items.get(0); e.setSessionStatus("G"); sess.saveOrUpdate(e); if ( ++count % 100 == 0 ) { sess.flush(); sess.clear(); } } tx.commit(); } catch (HibernateException asd) { if (tx != null) { tx.rollback(); } log.debug(asd.getMessage()); } finally { sess.close(); } } 

It is always recommended to perform bulk operations very close to the database, and we do not need to maintain the updated object in the session if they are not required. Therefore, try to avoid loading objects in a session when performing bulk operations.

+8
source share

All Articles