tomasz-mer
tomasz-mer

Reputation: 3920

How can I execute an update (named query) in Hibernate Template?

I have a namedQuery like this:

@NamedQueries ({ ...

@NamedQuery(name = "myUpdate", query = "update User set country = 'EN' where user.id = :id")

... })

In dao layer

getHibernateTemplate().bulkUpdate(...?)

UPDATE

Query query = sessionFactory.getCurrentSession.getNamedQuery("myUpdate");
getHibernateTemplate.bulkUpdate(query.getQueryString(), id);

I get an error:

Hibernate: update User, set country=EN where id = 2343 ORA-00971: missing SET keyword

Anybody now how can resolve this problem?

UPDATE 2

@NamedQuery(name = "myUpdate", query =
 "update User set country = 'EN' where
 user.profile.id = ?")

OK

  @NamedQuery(name = "myUpdate", query =
     "update User set country = 'EN' where
     user.profile.name = ?")

NOT OK :(

Upvotes: 2

Views: 31478

Answers (2)

Dominik
Dominik

Reputation: 829

Actually this is a very old question but I had the same problem today. I realized that the update does not work since you cannont have a join inside of a simple UPDATE. That is also the reason why the comma is added. Hibernate tries to rewrite the query like this:

UPDATE User u, Profile p SET u.country = 'EN' where p.name = ? AND p.id = u.profile.id

To solve the issue you need to select the ids from the second table yourself.

@NamedQuery(name = "myUpdate", query = ""
  + " UPDATE User u "
  + " SET country = 'EN' "
  + " WHERE u.profile.id IN ( "
  + "   SELECT p.id "
  + "   FROM Profile p "
  + "   WHERE p.name = ? "
  + " )"

Upvotes: 0

Augusto
Augusto

Reputation: 29897

Unfortunately, that feature is missing in spring, as the named queries are supposed to be used only to retrieve data. One thing you can do is (this is a bit of a work around)

Session session = getHibernateTemplate().getSession();
Query query = session.getNamedQuery("myUpdate");
String update = query.getQueryString();
getHibernateTemplate().bulkUpdate(update, [params]);

I would put that in some kind of helper, so your DAO logic doesn't have to go around spring too.

edit

there's a dangling comma between User and set "update User , set country=EN where"

Upvotes: 4

Related Questions