Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate HQL update with a subselect in set clause

I'm trying to do an update in hibernate HQL with a subselect in a set clause like:

update UserObject set code = (select n.code from SomeUserObject n where n.id = 1000)

It isnt working, it is not supported?

Thanks

Udo

like image 553
ssedano Avatar asked Oct 29 '25 08:10

ssedano


2 Answers

From the Hibernate documentation:

13.4. DML-style operations

...

The pseudo-syntax for UPDATE and DELETE statements is: ( UPDATE | DELETE ) FROM? EntityName (WHERE where_conditions)?.

Some points to note:

  • In the from-clause, the FROM keyword is optional
  • There can only be a single entity named in the from-clause. It can, however, be aliased. If the entity name is aliased, then any property references must be qualified using that alias. If the entity name is not aliased, then it is illegal for any property references to be qualified.
  • No joins, either implicit or explicit, can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the subqueries themselves may contain joins.
  • The where-clause is also optional.

While the documentation doesn't explicitly mentions a restriction about the set part, one could interpret that sub-queries are only supported in the where-clause. But...

I found an 4 years old (sigh) issue about bulk update problems (HHH-1658) and according to the reporter, the following works:

UPDATE Cat c SET c.weight = (SELECT SUM(f.amount) FROM Food f WHERE f.owner = c)

I wonder if using an alias in the from-clause would help. Looks like there is some weirdness anyway.

like image 99
Pascal Thivent Avatar answered Oct 31 '25 21:10

Pascal Thivent


I had the same problem, discovered that you need to put bulk updates in side a transaction:

tr = session.getTransaction();
tr.begin();
updateQuery.executeUpdate();
tr.commit;
like image 38
user1948182 Avatar answered Oct 31 '25 21:10

user1948182



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!