9

I am binding Named Parameters in a HQL statement, but it just doesn't get filled.

//colname = "AdminsInfo.name"; assume it is from method's input
//colval = input.getName().toString(); // assume it is from method's input

String query = "from AdminsInfo where :coln = :colv";
Query q = session.createQuery(query);
q.setParameter("coln",colname);
q.setParameter("colv",colval);

System.out.println(q.toString());        

it outputs something like this which means parameters (coln, colv) are not set and returns 0 records.

QueryImpl(from AdminsInfo where :coln = :colv)
Hibernate: select adminsinfo0_.Row as Row1_0_, adminsinfo0_.ID as ID2_0_,adminsinfo0_.Name as Name3_0_, ... where ?=?

Any help on how to bind column names in HQL statements are appreciated. Thanks. Mahdi.

2 Answers 2

12

You can't bind a column name as a parameter. Only a column value. This name has to be known when the execution plan is computed, before binding parameter values and executing the query. If you really want to have such a dynamic query, use the Criteria API, or some other way of dynamically creating a query.

Sign up to request clarification or add additional context in comments.

Comments

1

Try to replace Query for Criteria.

Criteria c = session.createCriteria(AdminsInfo.class);
c.add(Restrictions.eq(colname,colval));
c.list();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.