Named Queries in Hibernate

We have already learnt on how to integrate Hibernate with Spring MVC. Let’s learn to write named queries in Hibernate and try executing it in our application. Named queries are used to make the code more cleaner and organized, while keeping all the queries at one place and not scattered all over the code. Named queries can be used in two ways –

  • XML mapping file
  • Annotations

Before we proceed, let’s make sure we have the integration of Hibernate ready with Spring MVC.

Named Query is a better written HQL (Hibernate Query Language), where we opt to organize all our queries at one place instead of keeping it scattered all over the code.

We will be checking out how to use a named query with XML mapping file in this tutorial.

So let’s revisit the User.hbm.xml file that we had written and specify a query into it as –

Now we add a search form to our home.jsp file to allow searching user by ‘emailId‘ as –

Note that the search form action has been specified as ‘searchByEmail‘, for which we need to create a corresponding controller method to map the request.

Our new controller method to search user by their emailId looks as –

Service layer implementation of searchByEmailId method, internally makes a call to the DAO layer, whose implementation class has another searchByEmailId method that we have written as –

Below is a snapshot of how application looks like on running it –

Search implementation using Hibernate named queries

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.