问题
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