休眠和静态运行的HQL查询 [英] Hibernate and dry-running HQL queries statically

查看:90
本文介绍了休眠和静态运行的HQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想干运行Hibernate HQL查询。那就是我想知道Hibernate会从给定的HQL查询中执行什么样的实际SQL查询,而不是实际地对真实数据库执行HQL查询。

我有权访问Hibernate映射对于表,HQL查询字符串,方言< a>为我的数据库。



现在,我如何才能找出Hibernate可以从HQL生成的所有SQL查询,而无需实际执行查询数据库?有没有这方面的工具?



请注意,许多SQL查询可以从一个HQL查询生成,并且生成的SQL查询集可能会根据数据库的内容而有所不同。

我不问在HQL查询执行时如何记录SQL查询。



编辑:我不要不介意连接数据库来获取元数据,我只是不想执行查询。



编辑:我也知道限制和偏移量应用于查询。我也有绑定到查询的实际参数。 解决方案

简短的答案是你不行。答案如下。



您可以采取两种方法:

A)看看 HQLQueryPlan class ,特别是它的 getSqlStrings()方法。它不会让你成为精确的 SQL,因为在实际执行查询(参数被绑定,应用限制/偏移等等)之前会涉及到进一步的预处理,但它可能足够接近你想要。



这里要记住的是,您需要一个实际的 SessionFactory 实例构建 HQLQueryPlan ,这意味着如果没有连接到任何数据库,您将无法做到这一点。您可以使用内存数据库(SqlLite等),并让Hibernate为它自动创建必要的模式。



ASTQueryTranslatorFactory 有是更好的方法。


I'd like to "dry-run" Hibernate HQL queries. That is I'd like to know what actual SQL queries Hibernate will execute from given HQL query without actually executing the HQL query against real database.

I have access to hibernate mapping for tables, the HQL query string, the dialect for my database. I have also access to database if that is needed.

Now, how can I find out all the SQL queries Hibernate can generate from my HQL without actually executing the query against any database? Are there any tools for this?

Note, that many SQL queries can be generated from one HQL query and the set of generated SQL queries may differ based on the contents of database.

I am not asking how to log SQL queries while HQL query is executing.

Edit: I don't mind connecting to database to fetch some metadata, I just don't want to execute queries.

Edit: I also know what limits and offsets are applied to query. I also have the actual parameters that will be bind to query.

解决方案

The short answer is "you can't". The long answer is below.

There are two approaches you can take:

A) Look into HQLQueryPlan class, particularly its getSqlStrings() method. It will not get you the exact SQL because further preprocessing is involved before query is actually executed (parameters are bound, limit / offset are applied, etc...) but it may be close enough to what you want.

The thing to keep in mind here is that you'll need an actual SessionFactory instance in order to construct HQLQueryPlan, which means you won't be able to do so without "connecting to any database". You can, however, use in-memory database (SqlLite and the likes) and have Hibernate auto-create necessary schema for it.

B) Start with ASTQueryTranslatorFactory and descend into AST / ANTLR madness. In theory you may be able to hack together a parser that would work without relying on metadata but I have a hardest time imagining what is it you're trying to do for this to be worth it. Perhaps you can clarify? There has to be a better approach.

这篇关于休眠和静态运行的HQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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