1

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

Cichy
  • 1,319
  • 3
  • 20
  • 36

2 Answers2

5

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

Raul Rene
  • 10,014
  • 9
  • 53
  • 75
5

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.

Maddy
  • 923
  • 5
  • 8