14

Pre-compiled queries are compiled and cached in advance by DB vendor (like oracle,sql server etc) so that they can be faster for successive calls like prepared statement.

In Hibernate Named queries are said to be pre-compiled at web server start up. Does it means all queries are fired at server startup itself so that they can be pre-compiled by DB vendor or pre-compilation has different meaning in hibernate context?

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
M Sach
  • 33,416
  • 76
  • 221
  • 314

1 Answers1

12
  1. The Hibernate Named queries are expressed in an object query language (JPQL or HQL), so Hibernate needs to translate them to SQL first. The named queries are stored in a NamedQueryRepository and each query is represented by a NamedQueryDefinition.

Because the user can dynamically add filters, query result limits, locks, and hints, Hibernate cannot pre-compile the HQL/JPQL until execution time.

  1. Hibernate also uses a PreparedStatement for each SELECT and DML statement so you can also get database statement precompilation if the JDBC driver supports it and doesn't emulate the prepare phase by multiplexing the prepare and the execute in a single database request (e.g. MySQL, PostgreSQL).
Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • So vlad as you explained in point 1, Named queries are not precompiled in true sense. Agreed when using prepared statement in Hibernate, they are precompiled. – M Sach Dec 20 '14 at 06:56
  • After the first execution the will be cached on both Java and DB side. So it's not going to be a performance issue. – Vlad Mihalcea Dec 20 '14 at 07:20
  • 1
    Updated my answer. I browsed the source code and I found out that the named queries are translated at runtime, because Hibernate can also apply locks and filters. – Vlad Mihalcea Dec 20 '14 at 13:20
  • interesting Answer. How could one test if statement precompilation is effectively being used/supported by JDBC? – Shine May 09 '19 at 17:00
  • You can use a network proxy to inspect the traffic between the client and the DB. Anyway, it makes no sense to precompile a statement and use 2 different roundtrips if you are only going to execute a statement once. PostgreSQL has a threshold of execution until it switches to using prepared statements and not emulate them on the client side. – Vlad Mihalcea May 09 '19 at 17:03