Ni3
Ni3

Reputation: 359

How to write a query with "like" in the where clause in HQL?

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', then 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);

Upvotes: 22

Views: 104044

Answers (4)

Roman C
Roman C

Reputation: 1

Try this

List<RegistrationBean> registrations = session
    .createQuery("from RegistrationBean as rb where rb.:searchCriteria like '%:searchField%'", RegistrationBean.class) 
    .setParameter("searchCriteria", searchCriteria)
    .setParameter("searchField", searchField)
    .getResultList();

Here you set parameters by name using setParameter().

Upvotes: 9

rinuthomaz
rinuthomaz

Reputation: 1413

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+"%");
}

Upvotes: 13

Aleksandr M
Aleksandr M

Reputation: 24406

Change your query to this:

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

Upvotes: 32

MayurB
MayurB

Reputation: 3649

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'.

Upvotes: 18

Related Questions