I\'m \"transactionalizing\" some extensive database manipulation and I came across this issue where if I run sql queries through hibernate but not using the MQL approach, th
Your question is confusing, but I assume you are saying that Hibernate is not looking for entities in the Session cache when you are performing Native queries.
SQL Query, or Native Query, is a query which Hibernate just relays to the database. Hibernate won't parse the query, and it won't parse the results. Hibernate will, though, let you handle the results, to convert the columns into properties of a class. That said, it sounds quite natural that Native Queries would bypass the Session cache. That's because Hibernate doesn't knows anything about your query, nor about the "results" of this query (which are not objects at that point).
Actually the "explanation" blog by Chris Landry misses 3 important API methods of SQLQuery and thats in fact why he has those problems. Specifically, (1) addSynchronizedQuerySpace, (2) addSynchronizedEntityName and (3) addSynchronizedEntityClass
As partenon points out, just based on the SQL query string itself Hibernate has no way to know what tables and/or entities are queried in the query. Therefore, it has no idea what changes queued up in the Session need to be flushed to the database. In the blog Chris does point out that you can perform a flush() call on your own prior to running the SQL query. However, what I am describing is Hibernate's auto-flush capability. It actually does the same thing for HQL and Criteria queries. Only there it knows the tables being affected. Anyway, this process of auto-flushing does a "minimal flush" flushing only things that affect the query. Thats where these methods come into play.
As an example, Chirs's SQL query is
session.createSqlQuery("select name from user where name = :userName")
Really all he needed to do was to say...
session.createSqlQuery("select name from user where name = :userName")
.addSynchronizedQuerySpace( "user" )
The addSynchronizedQuerySpace( "user" )
is telling Hibernate that the query uses a table named "user". Now Hibernate can auto flush all changes pending for entities mapped to that user table.