32

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!

user964904
  • 885
  • 3
  • 9
  • 9

2 Answers2

40

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.

ChssPly76
  • 99,456
  • 24
  • 206
  • 195
25

Advantages

  • compiled and validated at app start-up time
  • easier to maintain than string literals embedded in your code
  • HQL and native SQL queries can be used and replaced without code changes (no need to re-compile your code)

Disadvantages

  • static
  • result-set mapping with native SQL queries sometimes cumbersome

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

tscho
  • 2,024
  • 15
  • 15