HQL更新的问题

时间:2011-07-26 06:35:27

标签: java hibernate

当我尝试执行以下HQL查询时:

Query  query =  getSession().createQuery("update XYZ set status = 10");
query.executeUpdate();

我得到了这个例外:

Exception in thread "main" org.hibernate.QueryException: query must begin with SELECT or FROM: update

编辑:
我也试过跟随。但它也没有用。

org.hibernate.Query  query =  getSession().createQuery("update XYZ t set t.status = 10");

EDIT2: 在hinbernate.cfg.xml中进行更改解决了我的问题 早些时候我正在使用

setting hibernate.query.factory_class"   = org.hibernate.hql.classic.ClassicQueryTranslatorFactor

现在使用以下属性

<property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>

5 个答案:

答案 0 :(得分:5)

这不是HQL查询。 您想导入允许正常 sql的javax.persistence.Queryorg.hibernate.Query不适用于entity objects

如果你想使用简单的sql,你也可以使用PreparedStatement

但是,如果你真的想使用hibernate,而不是利用entityobjects(首先完全无法使用hibernate,imho),你可以这样做(reference docs):

String myUpdate = "update XYZ myAlias set myAlias.status = :newStatus";
// or String noAliasMyUpdate = "update XYZ set status = :newStatus";
int updatedEntities = getSession().createQuery(myUpdate) //or noAliasMyUpdate
        .setInt( "newStatus", 10 )
        .executeUpdate();

答案 1 :(得分:3)

问题是在SQL中思考,何时应该考虑对象:

XYZ xyz = new XYZ();
xyz.setStatus(10);
getSession().merge(xyz);

答案 2 :(得分:0)

尝试:

Query  query =  getSession().createQuery("update XYZ o set o.status = 10");
query.executeUpdate();

同时查看this

答案 3 :(得分:0)

Session sesssion = getSession(); //getter for session

对于HQL:

String hql = "update Activity " +
"set startedOn = :taskStartedOn " +
"where id = :taskId";

Query query = session.createQuery(hql);
query.setDate("taskStartedOn",new Date());
query.setLong("taskId",1)
int rowCount = query.executeUpdate();

这里的活动是POJO。

答案 4 :(得分:0)

使用

hibernate.query.factory_class = org.hibernate.hql.ast.ASTQueryTranslatorFactory
hibernate.cfg.xml文件中

来解决异常:

org.hibernate.QueryException: query must begin with SELECT or FROM: update.....