Reputation: 34424
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.
Upvotes: 7
Views: 7818
Reputation: 691755
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.
Upvotes: 11