I am using hibernate and wanted to use named queries. but i dont know whether it is good solution or not? please provide me the advantages of named queries.
When named queries are compiled? can we directly change named query in hbm file which is deployed in application server?
Please help me.
Thanks!
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.
A named query is a predefined query that you create and associate with a container-managed entity (see "Using Annotations"). At deployment time, OC4J stores named queries on the EntityManager . At run time, you can use the EntityManager to acquire, configure, and execute a named query.
Native query refers to actual sql queries (referring to actual database objects). These queries are the sql statements which can be directly executed in database using a database client. Similar to how the constant is defined. NamedQuery is the way you define your query by giving it a name.
Named queries are more optimal (they are parsed/prepared once). Criteria queries are dynamic, (they are not precompiled, although some JPA providers such as EclipseLink maintain a criteria prepare cache).
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. The other advantage is that they're easy(-ier) to maintain - certainly for complex queries.
The disadvantage is that named queries are not customizable at runtime - you can define / supply parameters, of course, but beyond that what you've defined is what you'll get; you can't even change the sorting. Another disadvantage is that you will not be able to change the named query within a running application server without reloading the SessionFactory.
Advantages
Disadvantages
So, I think you should definitely prefer named queries over string literals in your code. When you need some kind of dynamic query creation at runtime you should take a look at the Hibernate Criteria API. Hibernate Criteria is not always easy and intuitive to use, but you should definitely use it instead of generating query strings at runtime.
HTH
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