Home > Blockchain >  How to optimize the Hibernate execution time?
How to optimize the Hibernate execution time?

Time:10-05

I have a Spring Batch application packaged as a JAR file as highlighted below

java -Xms2048m -Xmx2048m -Ddivision=25 -Ddate= -Denv=dv -Dconn=45 -jar demo-jobs*.jar job-definition.xml jobName -next

I want to optimize the overall execution time, so I'm trying to trace the average execution time for all the methods. I am using Java Flight Recorder.

I see that the following Hibernate methods taking high execution percentage

  1. Org.hibernate.query.Query.getResultList()
  2. Org.hibernate.query.internal.AbstractProducedQuery.list()
  3. Org.hibernate.query.SessionImpl.executeUpdate(String, QueryParameters)

enter image description here

enter image description here

What does it mean? How do I optimize this?

CodePudding user response:

This means that a lot of time is spent running SQL queries, which is often the case on a typical CRUD application.

Query.getResultList() relates to select queries, and SessionImpl.executeUpdate() relates to update or delete queries.

In order to understand what's happening, you'll have to find which queries are executed. There are many ways to do this, but my two favorites are:

  • You can log SQL statements in Hibernate, this will produce a log for each query that is run. Depending on your application, this might log lots of queries, perhaps too much to be of any use.
  • You can use a profiler like YourKit (a commercial product, but it has a 15-days trial which should be enough for your problem). In addition to CPU/memory analysis, YourKit can also monitor queries run via JDBC. It will basically list all the queries that were executed, how many times each of them was run, and what method executed them.

Once you have the detail of all the SQL queries that were executed, you'll have to check if it's consistent with what your application should do.

Problems that could occur:

  • N 1 queries
  • A missing index on column(s) that are used in where clauses (note that foreign keys are not automatically indexed on some databases)
  • A process that fetches data from some configuration table in a loop, instead of fetching the data once at the beginning
  • ...
  • Related