使用hibernate批量更新行

时间:2015-10-16 15:49:54

标签: java mysql hibernate

我正在使用hibernate 4.3.10。根据hibernate文档(13.4),应该支持DML样式更新。谁能指出我做错了什么?我有以下代码:

Session session = CurrentJobContextUtil.getCurrentContext().getSession();
Query query = session.createQuery("update Survey s set s.state = :newState where s.endDate < :time and s.state != :newState");
query.setParameter("newState",newState);
query.setDate("time", time);
int count = (int)query.uniqueResult();

我得到了例外:

org.hibernate.hql.internal.QueryExecutionRequestException: Not supported for DML operations [update com.customerconnect.jobmanager.data.model.Survey s set s.state = :newState where s.endDate < :time]
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.errorIfDML(QueryTranslatorImpl.java:318)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:369)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:236)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1300)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
    at org.hibernate.internal.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:966)
    at com.customerconnect.jobmanager.data.dao.SurveyDAOImpl.updateSurveyState(SurveyDAOImpl.java:26)
    at com.customerconnect.jobmanager.CCJobDataSvc.expireSurveys(CCJobDataSvc.java:510)
    at com.customerconnect.jobmanager.jobs.SurveyJobs.expireSurveys(SurveyJobs.java:30)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

1 个答案:

答案 0 :(得分:0)

(int)query.uniqueResult()更改为query.executeUpdate();,它会返回受影响的行数。