如何从 Hibernate Criteria API 获取 SQL(*不* 用于日志记录) [英] How to get SQL from Hibernate Criteria API (*not* for logging)

查看:25
本文介绍了如何从 Hibernate Criteria API 获取 SQL(*不* 用于日志记录)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从 Hibernate Criteria 中获取(要生成的)SQL?

Is there a way to get the (to-be-generated) SQL from a Hibernate Criteria?

理想情况下,我会有类似的东西:

Ideally, I would have something like:

Criteria criteria = session.createCriteria(Operator.class);

... build up the criteria ...
... and then do something like ...

String sql = criteria.toSql()

(But this of course does not exist)

然后想法是使用 SQL 作为巨大的减"查询的一部分(我需要找到 2 个相同模式之间的差异 - 结构相同,而不是数据 - 并且 Hibernate 不支持 MINUS)

The idea would then be to use the SQL as part of a huge 'MINUS' query (I need to find the differences between 2 identical schemas - identical in structure, not in data - and the MINUS is not supported by Hibernate)

(顺便说一句,我知道我可以从日志文件中检查 SQL)

(BTW I know I can check the SQL from the log files)

推荐答案

我已经使用 Spring AOP 完成了类似的事情,因此我可以获取应用程序中运行的任何查询的 sql、参数、错误和执行时间,无论是是 HQL、标准或本机 SQL.

I've done something like this using Spring AOP so I could grab the sql, parameters, errors, and execution time for any query run in the application whether it was HQL, Criteria, or native SQL.

这显然是脆弱的、不安全的,容易因 Hibernate 等的变化而中断,但它说明了可以获得 SQL:

This is obviously fragile, insecure, subject to break with changes in Hibernate, etc, but it illustrates that it's possible to get the SQL:

CriteriaImpl c = (CriteriaImpl)query;
SessionImpl s = (SessionImpl)c.getSession();
SessionFactoryImplementor factory = (SessionFactoryImplementor)s.getSessionFactory();
String[] implementors = factory.getImplementors( c.getEntityOrClassName() );
CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable)factory.getEntityPersister(implementors[0]),
    factory, c, implementors[0], s.getEnabledFilters());
Field f = OuterJoinLoader.class.getDeclaredField("sql");
f.setAccessible(true);
String sql = (String)f.get(loader);

将整个内容包裹在 try/catch 中,并自行承担使用风险.

Wrap the entire thing in a try/catch and use at your own risk.

这篇关于如何从 Hibernate Criteria API 获取 SQL(*不* 用于日志记录)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆