Update multiple rows using hibernate Criteria

杀马特。学长 韩版系。学妹 提交于 2019-12-21 04:34:19

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/24847466/update-multiple-rows-using-hibernate-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!