How to write a like query in HQL [duplicate]

2019-02-12 08:50发布

This question already has an answer here:

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);

标签: hibernate hql
5条回答
时光不老,我们不散
2楼-- · 2019-02-12 09:33

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楼-- · 2019-02-12 09:40

Change your query to this:

Query qry = session.createQuery("From RegistrationBean as rb where rb."+searchCriteria+"  like ?");
qry.setString(0, "%"+searchField+"%");
查看更多
虎瘦雄心在
4楼-- · 2019-02-12 09:40
Query qry = session.createQuery("From RegistrationBean as rb where rb."+searchCriteria+" like :sf");
qry.setString("sf",'%'+searchField+'%');

The above thing worked for me :)

查看更多
一纸荒年 Trace。
5楼-- · 2019-02-12 09:43

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+"%");
}
查看更多
虎瘦雄心在
6楼-- · 2019-02-12 09:50

This way

createQuery("from RegistrationBean as rb where rb.:searchCriteria like '%:searchField%'"); 
查看更多
登录 后发表回答