Using Named Parameters


What are Named Parameters?

HQL (Hibernate query language) contains two types of parameters, Positioned parameters and Named parameters. But HQL suggests Named parameters as it is more powerful and flexible than Positioned parameters. As its name suggests in the Named parameter mechanism, we can put a query in a variable and use that variable. One of the most significant advantages of this mechanism is that you can use the same variable many times in the program, which reduces your code.

How to implement Named parameters?

There are various ways to implement Named parameter mechanism,

  1. setParameter : Discover the parameter data type for you
    String hql = “from Emp where e.empid = :empid”
    List result = session.createQuery(hql);
    .setParameter(“empid”,”7277”)
  2. setString : set the data type to string
    String hql = “from Emp where e.empid = :empid”
    List result = session.createQuery(hql);
    .setString(“empid”,”7277”)
    .list();

Advantages of Named Parameters

  1. Easier to maintain the code.
  2. HQL or SQL commands can be used anywhere we want without changing the code.
  3. Named queries compiled when your application starts.

Future Scope of HQL

HQL is an advanced language than HQL, based on object-oriented mechanisms. It uses objects to store the data. Named Parameter is one of those popular features which make HQL stronger. To implement features like this, you have to learn HQL properly, and there are various options to learn HQL online.