Hibernate Criteria, Integer and “like”

最后都变了- 提交于 2019-12-01 15:58:01

问题


I'm migrating some of my hql-statements to Criterias now I'm figuring one problem: The entity property is type Integer but I need a like with wildcards search, so in hql I do

session.createQuery("from P1 where id like :id").setString("id", "%"+s+"%")

No problem at all, Hibernate casts String to Integer.

If I try this in Criteria, I only get a ClassCastException

String cannot be cast to Integer

Criteria crit = sessionFactory.getCurrentSession().createCriteria(P1.class);
crit.add(Restrictions.like("id",s)).addOrder(Order.asc("id")).setMaxResults(maxResults);

Why does Hibernate handle both situations differently?


回答1:


You could use the str expression conversion. If this makes any sense.

str() for converting numeric or temporal values to a readable string

session.createQuery("from P1 where str(id) like :id").setString("id", "%"+s+"%")

This will be quite slow if you do not have a function based index on the column.



来源:https://stackoverflow.com/questions/1859440/hibernate-criteria-integer-and-like

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