简体   繁体   中英

Hql Query to Bind a Data Member

Query qry = session.createQuery("From RegistrationBean where ? = ?");
qry.setString(0,searchCriteria);
qry.setString(1,searchField);
searchList =(ArrayList<RegistrationBean>) qry.list();

RegistrationBean Entity class has userName, address, age fields.. I want to search a user by search criteria such as userName, address etc. using the above single query... But the query is returning me zero results even though the user exist..

what's the problem?

Both parameters are set to 0 position, the second is not set. The position parameter should be set sequentially.

qry.setParameter(0,searchCriteria);
qry.setParameter(1,searchField);

But the field name should pass in the following way

String queryString = "from RegistrationBean as model where model." + propertyName   + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();

Try in the following way:

Query qry = session.createQuery("select * from RegistrationBean where :searchCrit = :searchValue");
qry.setString(":searchCrit",searchCriteria);
qry.setString(":searchValue",searchField);
searchList =(ArrayList<RegistrationBean>) qry.list();

It is more appropriate to use it like this instead of setting indexes (your problem is that you set both to 0), because if you change something in your query you might need to change your setters afterwards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM