简体   繁体   中英

Hibernate and prepared statement

As far as I could find from google, hibernate uses PreparedStatement for its queries.

I need to execute a query consisting of two parts, the first part of which could be written in hibernate criteria and the second one is a dblink query, therefore hibernate cannot be used.

So, I would like to extract the PreparedStatement object from the Criteria object.

Criteria criteria = getSession().createCriteria(Entity.class);
//adding restrictions
PreparedStatement stmt;
//initializing stmt with criteria's PreparedStatement

How can I do that? Is it even possible?

This is not possible with the current Hibernate API. And it would be difficult to add support for it anyway. For example, to execute getSession().createCriteria(Entity.class) without any other restrictions, Hibernate may need to produce more than one PreparedStatement (to fetch Entity and all of its associations, based on defined fetch plan and strategy for Entity class).

Also, it would be difficult for you to implement and maintain such a solution event if something like that existed. You may need to parse the generated statements to be able to 'inject' your part of the query. Or the generated statements may change when you modify your entities or depending on the current state of persistence context (something that's already in the session is not fetched again, so the queries are different etc). You would also need to be careful when upgrading Hibernate to a new version because the exact structure of the generated queries may change.

There are probably many other obstacles that would make it hard to achieve this for the time being, but I think that your reasoning is good, and hopefully Hibernate will expose some kind of API in future which will allow us to have greater influence on the generated SQL.

Create a view that uses the dblink query in the same schema as your table.

Then create an entity that maps to your view.

You can then create a DetachedCriteria to use as a subselect in your criteria query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM