As hibernate document says that purpose of named query is to clear the HQL from different places in project to single place in some xml (in case of declarative approach).This means no recompilation is required n case of query modification but reloading of session factory is required which means server start up in most of the cases as query object is cached. But in case of annotation i need to define the named queries at entity level. So here compilation again requires. My question here is does named query help in performance also. Here is my understanding:-
1)when i use named queries, just query object is cached in second level cache. When i say just query object it means just query syntax is cached not the query results.Right? If its right then probably its useful only in case of HQL becoz thats where we can avoid traslation of HQL to native query ,every time query is fired and have some good time performance.
But if we are using native sql, named query does not provide that advantage as no translation happens in that case.
So main advantage of named query is to make central repository of sqls. Yes in case of HQL it can save us some translation time to native sql also but keep in mind that query object will lie for the life time of jvm and will consume some memory. So some trade off here.
Hibernate named queries provide a data access and manipulation mechanism that closely ties the query content to the Java code defining the objects that the query is executing against. It also removes the actual query language from Java code, which is a common tactic and creates certain maintainability issues.
Named Query Parameters may be bound to Tags or other properties on the same window, allowing your users to modify the resulting dataset by manipulating other components similar to the original SQL Query binding type. You can also select and update a query to simulate a bi-directional binding to the database.
Named queries are compiled when SessionFactory is instantiated (so, essentially, when your application starts up). The obvious advantage, therefore, is that all your named queries are validated at that time rather than failing upon execution.
A named query is a statically defined query with a predefined unchangeable query string. They're validated when the session factory is created, thus making the application to fail fast in case of an error.
Named queries have two small advantages:
They also have a drawback: when reading or debugging code using a named query, you can"t immediately see which query is being executed without searching for its definition.
The rest is really unimportant:
I tend to prefer defining the query in the code where it's used, and to unit test them. That makes the code more readable, and more robust.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With