views:

1229

answers:

2

How to build valid HQL string, which is equivalent to

UPDATE table SET field = null WHERE ....

+1  A: 

Do you mean bulk HQL update? Try this

UPDATE myEntity e SET e.myProperty = null WHERE ...

You can also use a parameterized version of the above

UPDATE myEntity e SET e.myProperty = :param WHERE ...

In your code:

int updatedEntities = session.createQuery(updateQueryHQL)
  .setString( "param", myValue ) // or .setString( "param", null )
  .executeUpdate();

See documentation for details.

If you're not doing bulk updates, you should just set your property to NULL and persist the entity normally.

ChssPly76
Thanks, but ... both versions throw HibernateException !!! setString( "param", myValue )executeUpdate();works only when myValue is not null !!!
What kind of HibernateException (what does the error say)? Does your table allow NULLs in that column? Is that property actually a String or is it of some other type?
ChssPly76
1. The table column allow NULLs2. The property is actually String (this same problem with column of type 'Date')2. Hibernate Exception error unfortunately is invalid ('UPDATE permission missing on object .....). Isn't true : in case myValue is empty string or not null value - the requested column is updated without troubles
Can you update your question and post 1) full stack trace of hibernate exception and 2) SQL as generated by hibernate (you may need to set `hibernate.show_sql` property to true, if you haven't already). I've used bulk update to set values to NULL before and it worked with no problems - the issue is with your setup, not with Hibernate itself.
ChssPly76
A: 

Why does your update statement need to be done in HQL? Do you have this table mapped to an entity in the system? If you do, then you can simply set the property that maps to that column to null, and run a save on that entity. eg.

myObject.setMyProperty(null); getSessionFactory().getCurrentSession().save(myObject);

That should work for you, but you gotta have an entity mapped to the table in question.

Zoidberg