EclipseLink/JPA:如何以编程方式获取已执行的SQL查询的数量 [英] EclipseLink / JPA: How to programmatically get the number of SQL queries that have been performed

查看:69
本文介绍了EclipseLink/JPA:如何以编程方式获取已执行的SQL查询的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过EclipseLink使用JPA.在单元测试中,我想测试在一次操作中执行了多少个SQL查询.这样,如果以后的修改导致查询数量激增(例如,如果触发了延迟加载),则单元测试会将其标记为可能需要优化.

I'm using JPA, by way of EclipseLink. In my unit tests, I'd like to test how many SQL queries were performed during an operation. That way, if a later modification causes the query count to explode (if lazy loading is triggered, for instance), the unit test will flag it as potentially needing optimization.

我正在寻找正确的API来做到这一点.纯JPA解决方案将是理想的选择,但是我可以在单元测试中使用EclipseLink特定的API.我看了看EclipseLink分析器,但是它似乎没有给我一种计算SQL查询数量的方法.

I'm striking out in finding the correct API to do this. A pure-JPA solution would be ideal, but I'm fine with using EclipseLink-specific APIs in my unit tests. I looked at the EclipseLink profiler, but it doesn't seem to give me a way to count the number of SQL queries.

提前感谢您的帮助!

推荐答案

我没有找到用于这种验证的合适工具,而是创建了自己的工具.它被称为 sniffy ,并且已获得MIT许可.

I didn't find a proper tool for such validation and created my own. It is called sniffy and available under MIT license.

您可以声明生成的查询数量,如下所示:

You can assert the number of generated queries like shown below:

// Integrate Sniffy to your test using @Rule annotation and a QueryCounter field
@Rule
public final QueryCounter queryCounter = new QueryCounter();

// Now just add @Expectation or @Expectations annotations to define number of queries allowed for given method
@Test
@Expectation(1)
public void testJUnitIntegration() throws SQLException {
    // Just add sniffer: in front of your JDBC connection URL in order to enable sniffer
    final Connection connection = DriverManager.getConnection("sniffer:jdbc:h2:mem:", "sa", "sa");
    // Do not make any changes in your code - just add the @Rule QueryCounter and put annotations on your test method
    connection.createStatement().execute("SELECT 1 FROM DUAL");
}

有关与JUnit集成的更多信息,请参见项目Wiki

More information about integration with JUnit available in project wiki

这篇关于EclipseLink/JPA:如何以编程方式获取已执行的SQL查询的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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