Hibernate Criteria API condition “like” with integer

六眼飞鱼酱① 提交于 2019-12-24 07:17:13

问题


In my database I have a column "year" which is an integer.

How can I search by using Criteria API (not by HQL) which records contain, for example "196..." in the year column?

I think it should be Restrictions.like, but I got exception:

SEVERE: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer


回答1:


a better and faster solution would be to use Criterion.sqlRestriction(String sql). You can form the sql as, "to_char(year) like '19%'", be aware that to_char is database specific. I dont think JPA supports to_char function.




回答2:


Actually, the exception should tell you everything you need. The Restrictions.like in your case is looking for an Integer, but got a String as a parameter. (you should have posted the exact call of the Restrictions.like used).

Nevertheless there is a Restrictions.between method. You could use that for your problem. For example:

criteria.add(Restrictions.between("year", 1960, 1970));

There are also alternative methods. Integers can be compared with Restrictions.le (less or equal), Restrictions.lt (less than), Restrictions.gt (greater than), Restrictions.ge (greater or equal).



来源:https://stackoverflow.com/questions/12841531/hibernate-criteria-api-condition-like-with-integer

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