Vishrant
Vishrant

Reputation: 16628

How to set generic parameter to Query object of Hibernate?

I have created a generic method which will take hibernate named query, a HashMap object which contain parameter name values for that named query in the following manner:

The method signature is:

public static <T> ArrayList<T> getData(String hibernateQueryName, HashMap<?, ?> 
                                             queryNameValue) throws Exception;

Now suppose I have a SQL and its hibernateQueryName is empData:

SELECT e.emp_nm      AS EMP_NAME
     , e.emp_address AS EMP_ADDR
  FROM employee e
 WHERE e.emp_no > :empNumber
   AND e.name LIKE :empName

Here empNumber and empName are parameter name and they are of type Integer and String respectively.

Now suppose I have one more SQL and its hibernateQueryName is studentData:

SELECT s.s_nm    AS EMP_NAME
  FROM student s
 WHERE s.dob > :studentDOB

Here studentDOB is parameter name and its of type Date. studentDOB is a key that I will get from HashMap.

I want to set these parameter and values to query object like:

Query query = getSession().getNamedQuery(hibernateQueryName);
query.setXXX(parameterName, parameterValue);

Above code is written in my getData method.

There are many query.setXXX methods which are based on Type for example query.setInteger() but for calling this I need to find the type of ? which I am passing in getData method. Is it possible to use query.setXXX method with unknown type ?

Upvotes: 1

Views: 2458

Answers (2)

Prakash Bhagat
Prakash Bhagat

Reputation: 1446

The signature of query.set parameter is

void QueryInstance.setParameter(String, Object);

You may use HashMap<String,Object> as parameter, iterate it in method and assign as per the mentioned method. It will act as generic. I have made generic that way, it may help in your case as well.

Upvotes: 1

Jordan.J.D
Jordan.J.D

Reputation: 8113

Try using query.setParameter("name", value) this does not expect an explicit type.

Upvotes: 1

Related Questions