Using LIKE % in Hibernate

无人久伴 提交于 2019-12-02 02:07:32

问题


How do I use LIKE % in Hibernate. I want to use a SQL with LIKE % in my hbm.xml file. I have 2 queries which I am consolidating to 1.

The query looks like this:

select * from PAY_GROUP_VW where CASE_SID=? AND CASE_TLE like %?%

I also tried %?%. I have used like clause without % and it works. But % does not work.

Wrapped exception:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
    at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:630)
    at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424)
    at org.springframework.orm.hibernate3.HibernateTemplate.executeFind(HibernateTemplate.java:343)

This is how I pass the parameters:

q.setParameter(0, csId);
q.setParameter(1, csTle);
return q.list();

Tried like % || ? and got the following exception:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query
    at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:630)
    at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
    at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:424)
    at org.springframework.orm.hibernate3.HibernateTemplate.executeFind(HibernateTemplate.java:343)

回答1:


Maybe the user_id is not a char/varchar? You have to convert the user_id with str() to character data first!

Example:

SELECT *
FROM abc.def_vw a
WHERE user_id = ?
AND str(user_id) LIKE '%' || ?



回答2:


Use LIKE '%?%' and second parameter string to make the query. The field also should be a string type because like is used to compare strings.




回答3:


3 things to notice:

  • Is user_id string?
  • like in HQL works fine. for example like '%something%'
  • Your query doesn't make sense "where user_id =? and user_id like '%'" what are you trying to do ? Use only one of the conditions.


来源:https://stackoverflow.com/questions/15369090/using-like-in-hibernate

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