Hibernate Named Query Using Like and % % operators?

Java Developer picture Java Developer · Jan 2, 2013 · Viewed 85.7k times · Source

In my Hibernate JPA Sample code..

public List<AttendeesVO> addAttendees(String searchKeyword) {
    TypedQuery<AttendeesVO> query = entityManager.createQuery(" select at from AttendeesVO at where at.user.firstName LIKE :searchKeyword",AttendeesVO.class);
    query.setParameter("searchKeyword", searchKeyword+"%");
    return query.getResultList();
}

it is working fine when giving entire String firstName=Narasimham

But it is not working when we give any character of Narasimham i.e a or n

Actually my thinking is i'm giving Like operator with % % so it working any character of given String..

Answer

Subin Sebastian picture Subin Sebastian · Jan 2, 2013

you are using query.setParameter("searchKeyword", searchKeyword+"%");

instead of query.setParameter("searchKeyword", "%"+searchKeyword+"%");

first one will return rows for Narasimham N Na Nar Nara etc.