Native query in Spring Boot / Hibernate much slower than executed externally

时间:2017-08-13 14:07:31

标签: java spring hibernate h2

I have multiple queries that I execute using entityManager.createNativeQuery(sqlQuery).getResultList() which take tens of seconds (up to a couple of minutes) to execute. I enabled Hibernate logging and executed the very same SQL queries in IntelliJ connecting to the same database. The queries returned in less than 10ms.

The database is embedded H2, the database driver is the same. The queries do not contain any parameters (which eliminates this). They only return integers (IDs and counts). If I execute the queries two times in a row the second query returns nearly instantaneous. The query execution time is the same whether I allocate 128M or 2048M to the JVM.

The queries don't look too complicated. The only thing I noticed is that someof them have inner select statements on which I join or which I compare with. I guess they're not the actual problem because they can be executed very quickly when not executed from my program.

The rest of the program works just fine and there are other queries which run as fast expected.

This is an example query:

SELECT
  USER_ID,
  count(result) AS count
FROM USERAPIACCESS
WHERE USER_ID IN (123)
      AND RESULT IN ('SUCCESSFUL')
GROUP BY USER_ID, RESULT
ORDER BY USER_ID, RESULT

1 个答案:

答案 0 :(得分:0)

此表中有多少条记录? 我认为问题是你在这里没有分页,应用程序将获取此表中存在的所有记录