I'm trying to convert an old application executing SQL queries the old way as below:
java.sql.Connection connection = ....
String queryStr="select acct from Person where acct in (select acct from Document where dbcreate_date > DATEADD(hh,-12, GETDATE())) and status not in ('A','P')";
...
...
java.sql.Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = statement.executeQuery(queryStr);
The above code takes about 10 milliseconds. This includes getting the database connection, creating the statement and executing the query.
I'm now using Hibenate HQL and created an HQL query like this:
Query query = session.createQuery("select p.acct from Person p where p.acct in (select acct from Document d where create_date > :date and status not in ('A','P'))");
Now just this statement "session.createQuery(....)" is taking about 105 milliseconds, which is about 10 times longer then doing the whole query stuff in the old way as mentioned above.
Now I'm not really sure how Hibernate query caching works, but if I run this same HQL statement a second time, it will take about 5 milliseconds.
Now my question is why is this behavior happening using Hibernate HQL? Anyone knows what is going on inside the "session.createQuery(...)" method that takes much longer the first time but much less the second time it runs? I also noticed that that Hibernate executes the SQL against the database both times when doing "query.list()".
Thanks.