Home > other >  Hibernate, MySQL, relationship between batches, JDBC connections and JDBC statements
Hibernate, MySQL, relationship between batches, JDBC connections and JDBC statements

Time:05-11

Currently working on an application which uses hibernate and MySQL. I saw the following output in my Logs which surprised me:

Hibernate: select user0_.id as id1_3_, user0_.email as email2_3_, user0_.name as name3_3_ from test_user user0_ order by user0_.name asc limit ?, ?
Hibernate: select count(user0_.id) as col_0_0_ from test_user user0_
2022-05-11 10:49:23.650  INFO 21384 --- [           main] i.StatisticalLoggingSessionEventListener : Session Metrics {
    441906 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    2709671 nanoseconds spent preparing 2 JDBC statements;
    8478990 nanoseconds spent executing 2 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    0 nanoseconds spent executing 0 flushes (flushing a total of 0 entities and 0 collections);
    16820 nanoseconds spent executing 2 partial-flushes (flushing a total of 0 entities and 0 collections)
}

I did not expect this output because:

  • There are 2 queries which correspond with the 2 JDBC statements
  • There are 0 batches
  • There is only one JDBC connection

What I expected was one of the following:

  • 1 batch, 2 statements, and one connection to execute the batch
  • 0 batches, 2 statements, 2 connections (one for each statement)

How is it possible to have 0 batches and still execute the 2 queries within one connection?

CodePudding user response:

It sounds like you think batch == transaction, but that is not the meaning used in JDBC. In Java/JDBC, batch execution has a specific meaning, and I assume that Hibernate uses the same meaning: executing multiple update/delete/insert statements using Statement.executeBatch(). That definitely doesn't apply here, because you can't batch selects in JDBC, and even for update/delete/insert you would generally only batch if there are multiple sets of parameters to execute on a single prepared statement.

Here, Hibernate executes the first statement, and then the second, on one and the same connection (and in the same transaction). Depending on the needs, it might interleave processing of the result sets of both select statements (JDBC allows multiple open result sets from different statement objects when not in auto-commit).

  • Related