How to use named parameters and named query in Hibernate?

Named Parameters in Hibernate Query

There is two types of query parameters binding in the Hibernate Query. One is positioned parameter and another one is named parameter. But, hibernate recommend to use the named parameters since it is more flexible and powerful compare to the positioned parameter. Here we will look into the named parameter type in detail.

also read:

Named parameters are as name itself suggests, the query string will be using the parameters in the variable name. That can be replaced at runtime and one advantage of using named parameter is, the same named parameter can be used many times in the same query.

String queryStr = "from Student s where s.name like :searchName";
List result = session.createQuery(queryStr)
              .setString("searchName",searchNameValue)
			  .list;

In the above code “:searchName” is the named parameter and it is dynamically added to the query string.

Another good feature is using the named query instead of writing the SQL queries every where. In the named query,all the queries are written inside the .hbm files. Each query is associated with a unique name. Application can load the query by using the name of that query. It avoids writing queries inside the java code itself. The method getNamedQuery() is used for retrieving the query from the mapping file.

session.getNamedQuery("findStudentByName")
        .setString("searchName",searchNameValue)
		.list();
<query name="findStudenetbyName"><![CDATA[
    from Student s where s.name like :searchName
]]></query>

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better