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 like :searchName";
List result = session.createQuery(queryStr)

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.

<query name="findStudenetbyName"><![CDATA[
    from Student s where like :searchName

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!