Monday, 9 January 2017

Hibernate Named Query and its advantages & disadvantages

Hibernate Named Query
If there are a lot of queries, then they will cause a code mess because all the queries will be scattered throughout the project(in java code). The hibernate named query is a technique to define a central location for all  queries and use them by some meaningful names/alias.

There are two ways to define the named query in hibernate:
by annotation
by mapping file.

Hibernate Named Query by annotation
@NameQueries annotation: is used to define the multiple named queries.

@NameQuery annotation: is used to define the single named query.

                  name = "findEmployeeByName"
                  query = "from Employee e where = :name" 

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.

Easier to maintain than string literals embedded in the code certainly for complex queries.

HQL and native SQL queries can be used and replaced without code changes (no need to re-compile your code)

static,  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.

We will not be able to change the named query within a running application server without reloading the SessionFactory.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...