简体   繁体   English

使用Hibernate时进行集成测试本机SQL查询

[英]Integration testing native SQL query when using Hibernate

I use Hibernate and widely adopted Hibernate Query Language to define queries in my DAOs. 我使用Hibernate和广泛采用的Hibernate查询语言在我的DAO中定义查询。

Anyway sometimes HQL isn't capable of performing specific task compared to native SQL query. 无论如何,与本地SQL查询相比,HQL有时无法执行特定任务。

For example the following Postgres expression is not "convertible" to HQL: 例如,以下Postgres表达式不能“转换为” HQL:

my_date > current_date - interval '10 year'

This means that in some case I'm writing native queries. 这意味着在某些情况下,我正在编写本机查询。 Considering that I'm using another database for integration testing ( http://hsqldb.org/ ) which doesn't reflect the syntax of the Postgres expression above. 考虑到我正在使用另一个数据库进行集成测试( http://hsqldb.org/ ),它不能反映上面Postgres表达式的语法。 This results in test exception during DAO methods using such native query. 这会导致在使用此类本机查询的DAO方法期间出现测试异常。

How do you handle such cases? 您如何处理这种情况? I can just think of following scenarios: 我可以想到以下情形:

  • Never use native query and try to build everything in HQL (possible?) 永远不要使用本机查询,并尝试在HQL中构建所有内容(可能吗?)
  • Don't test methods which use such queries (unhappy) 不要测试使用此类查询的方法(不满意)
  • Use same database both for production and development (performance problem) 将相同的数据库用于生产和开发(性能问题)

Other, more interesting solution? 其他更有趣的解决方案? Thanks 谢谢

Normally the purpose of integration testing is to test against (very) similar environment to production, hence IMO you should use the same database engine. 通常,集成测试的目的是针对(非常)与生产环境相似的环境进行测试,因此,IMO应该使用相同的数据库引擎。 For unit testing however using HSQLDB is fine. 对于单元测试,使用HSQLDB很好。 In which case unfortunately the classes that has dependency to Postgres couldn't be unit tested, you have to wait until integration testing to detect bugs. 不幸的是,在这种情况下,不能对依赖于Postgres的类进行单元测试,您必须等到集成测试才能检测到错误。

On a side note however the result of the Postgres SQL you mentioned can be achieved by performing the date arithmetic on Java. 附带说明一下,您提到的Postgres SQL的结果可以通过在Java上执行日期算术来实现。

Calendar currentDateCal = Calendar.getInstance();
currentDateCal.add(Calendar.YEAR, -10);
Date currentDate = currentDateCal.getTime(); // bind this currentDate object into your HQL parameter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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