views:

29

answers:

1

I have what may be a pretty elementary Hibernate question. Do HQL (and/or Criteria) update queries cause updates to live domain objects? And do they automatically flush now-invalid domain objects from the first-level cache?

Example:

Player playerReference1 = session.get(Player.class,1);
session.createQuery("update players set gold = 100").executeUpdate();
//Question #1 -- does playerReference1.getGold() now return 100?
Player playerReference2 = session.get(Player.class,1);
//Question #2 -- does playerReference2.getGold() return 100, or is it the same exact object?

Should I make a practice of evicting all objects that are affected by an HQL update if there's a chance some code will need it later?

+1  A: 

The answer to both questions is no. According to Java Persistence with Hibernate, chapter 12:

If you execute an SQL statement that operates directly on the rows in the database, any change you make doesn't affect the in-memory objects (in whatever state they may be). In other words, any direct DML statement bypasses the Hibernate persistence context (and all caches).

This applies to HQL as well. They recommend executing DML before loading any objects from the session.

Matt Solnit
But this is an HQL statement, not a SQL statement.
CaptainAwesomePants
Hrm...I had thought HQL statements were smarter than SQL statements in regards to the session cache. Apparently not. Thanks!
CaptainAwesomePants
This applies to HQL as well. I updated my answer.
Matt Solnit