How to write a like query in HQL [duplicate]

怎甘沉沦 提交于 2019-12-18 04:33:26

问题


I want to perform search for a particular string that is starting with a particular alphabet. So, for example if the starting alphabet is 'A' den it should produce a result which will contain all the strings with alphabet 'A'.

How do I achieve this ?

My query is as shown below

Query qry = session.createQuery("From RegistrationBean as rb where rb."+searchCriteria+"  like %?%");
qry.setString(0,searchField);

回答1:


Change your query to this:

Query qry = session.createQuery("From RegistrationBean as rb where rb."+searchCriteria+"  like ?");
qry.setString(0, "%"+searchField+"%");



回答2:


You can use criteria for using like

session = sessionFactory.openSession();
Criteria query = session.createCriteria(Pojo.class);
query.add(Restrictions.like("column", "a", MatchMode.START));

It will give you the list of string which start by alpha-bate 'a'.




回答3:


Change to

Query qry = session.createQuery("From RegistrationBean as rb where rb ";
if (searchField != null)
{
    qry = qry + " where rb.searchCriteria like :searchField ";
}
if ( searchField!= null)
{
    query.setString("searchField","%"+searchField+"%");
}



回答4:


This way

createQuery("from RegistrationBean as rb where rb.:searchCriteria like '%:searchField%'"); 



回答5:


Query qry = session.createQuery("From RegistrationBean as rb where rb."+searchCriteria+" like :sf");
qry.setString("sf",'%'+searchField+'%');

The above thing worked for me :)



来源:https://stackoverflow.com/questions/13562261/how-to-write-a-like-query-in-hql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!