Hibernate Named Query Using Like and % % operators?

会有一股神秘感。 提交于 2019-12-03 06:32:48

问题


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


回答1:


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.




回答2:


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

Because you are doing case sensitive search. Try N, Na, Nar instead. If you want to perform a case insensitive search try using upper or lower. like

entityManager.createQuery("select at from AttendeesVO at where lower(at.user.firstName) LIKE lower(:searchKeyword)",AttendeesVO.class);  

Actually my thinking is i'm giving Like operator with % %

searchKeyword+"%" means return values which starts with searchKeyword.
"%"+searchKeyword+"%" means return values which contains searchKeyword.
Decide as per your requirment.




回答3:


I would add my voice to @ssk to use two % before and after the keyword. Or I think its more professional solution if you configured it in the query itself like this :

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

because the '%' its part of the query not of the parameter what you may fill it out later

The CONCAT() function adds two or more expressions together. https://www.w3schools.com/sql/func_mysql_concat.asp



来源:https://stackoverflow.com/questions/14119241/hibernate-named-query-using-like-and-operators

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