Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem with HQL update

Tags:

java

hibernate

When I try to execute the following HQL query:

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

I get this exception:

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

EDIT:
I also tried following .But it doennot work either.

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

EDIT2: Making changes in hinbernate.cfg.xml solved my problem Earlier i was using

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

Now am using following property

<property name="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</property>
like image 704
akshay Avatar asked Jul 26 '11 06:07

akshay


1 Answers

Thats not an HQL query. You want to import javax.persistence.Query which allows normal sql, not org.hibernate.Query which works on entity objects.

If you want to use simple sql, you could also use PreparedStatement

However, if you really want to use hibernate, without taking advantage of entityobjects (totally defeating the point of using hibernate in the first place, imho) you could do it like this (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();
like image 65
NimChimpsky Avatar answered Oct 19 '22 17:10

NimChimpsky