ErrorNotFoundException ErrorNotFoundException - 3 months ago 27
Java Question

Update multiple rows using hibernate Criteria

I am trying to run an update query which would look like this in sql:

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


I am trying to re-create the query using Criteria like this:

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 is not working because the rows which meet this Criteria are many, my unique result is the problem here I guess.
How can I convert this into an update for all the rows that meet the Criteria. I do not want to use HQL query, I am rather doing it with Criteria.

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 suggested that execute bulk operations very close to database and we do not need keep updated object in session unless they are required, Hence try to avoid load objects in session while executing bulk operations.

Comments