Hibernate SQLQuery bypasses hibernate session cache

邮差的信 提交于 2019-11-29 07:47:19

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!