views:

11

answers:

1

Hi,

I've got a function with a session argument that does various HQL queries and HQL update statements in hibernate. They create sql that goes against alot of tables. All in one transaction.

Now what I want to do is add one entity that this function depends on, in another function, with session.save, and then call the first function. I'm worried that Hiberante won't cause the SQL associated with the session.save(myentity) before executing the HQL queries and updates that depend on the former. Some kind of caching in the session and reordering of statements.

Andy

A: 

I'm worried that Hibernate won't cause the SQL associated with the session.save(myentity) before executing the HQL queries and updates that depend on the former.

The documentation explains pretty well what causes a flush to occur:

10.10. Flushing the Session

Sometimes the Session will execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. This process, called flush, occurs by default at the following points:

  • before some query executions
  • from org.hibernate.Transaction.commit()
  • from Session.flush()

The SQL statements are issued in the following order:

  1. all entity insertions in the same order the corresponding objects were saved using Session.save()
  2. all entity updates
  3. all collection deletions
  4. all collection element deletions, updates and insertions
  5. all collection insertions
  6. all entity deletions in the same order the corresponding objects were deleted using Session.delete()

An exception is that objects using native ID generation are inserted when they are saved.

Except when you explicitly flush(), there are absolutely no guarantees about when the Session executes the JDBC calls, only the order in which they are executed. However, Hibernate does guarantee that the Query.list(..) will never return stale or incorrect data.

I don't know what your function is doing exactly, and in what order, but the documentation is explicit: executing a query will trigger a flush if required. I'm not sure this applies to bulk updates though (why is why I mentioned the order). But why don't you flush after the save if you want to be sure?

Pascal Thivent
I do a session.save(obj), query1.list(), query2.executeUpdate() several times, query3.list(), query4.executeUpdate() several more times. The first query.list() depends on the session.save() being seen and the second query.list() depends on the query.executeUpdate() being seen.
Andy Nuss