如何从Hibernate Criteria API获取SQL(* not * for logging) [英] How to get SQL from Hibernate Criteria API (*not* for logging)

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

问题描述



理想情况下,我会有这样的东西:

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

...建立标准...
...然后做类似...

String sql = criteria.toSql()

(但这当然不存在)

这个想法会是使用sql作为一个巨大的'MINUS'查询的一部分(我需要找出两个相同模式之间的差异 - 结构完全相同,而不是数据 - 而且HUS不支持MINUS)

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

解决方案

类似于使用Spring AOP的东西,所以我可以获取应用程序中运行的任何查询的SQL,参数,错误和执行时间,无论它是HQL,Criteria还是本机SQL。

这显然是脆弱的,不安全的,可能随着Hibernate等的变化而中断,但它表明可以获得SQL:

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

将所有东西包装在try / catch中,并自担风险。


is there an easy 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)

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)

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

解决方案

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.

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);

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

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

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