11

I have to do Restrictions.like("sequenceNo", "%" + Integer.valueOf(sequenceNo.trim()) + "%").

The field sequenceNo is integer type but the sequenceNo param value is string. My problem is I get an exception java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer. For some reasons I really have to make my param a string data type. When I tried it in SQL to LIKE an integer it works.

Please help. Thanks.

Kermit
  • 33,827
  • 13
  • 85
  • 121
kwan_ah
  • 1,061
  • 1
  • 12
  • 18
  • 2
    You cannot use `LIKE` with integer columns. If you absolutely want to do this you must cast the integer to a string before the `LIKE` is applied. This would be easy if you were writing your own SQL, but right now I'm too lazy to look up how to tell Hibernate to do that :-) – Jim Garrison Mar 20 '13 at 03:36

5 Answers5

9

You cannot add Criteria`s property restrictions for the purpose, as during fetching, property value specifiedwould be casted according to the 'field type' specified in Entity class.

However, a solution would be using SQLRestriction of criteria, to by pass casting. I have tested and this works.

yourDetachedCriteriaObj.add(Restrictions.sqlRestriction(" sequenceNo LIKE '%"+yourSequenceNumToSearch+"%' "));

To get list you would do like below

List ls = yourDetachedCriteriaObj.getExecutableCriteria(yourSession).list();
// iterate over list or do whatever.
maimoona
  • 617
  • 8
  • 16
2

i'm ashamed, but i did following workaround with postgres

crit.add(Restrictions.sqlRestriction(entry.getKey()+"::text like '%"+entry.getValue().replace("'", "''")+"%'"));
wutzebaer
  • 14,365
  • 19
  • 99
  • 170
0

My postgres modification

cr34.add(Restrictions.sqlRestriction(cr34.getAlias()+"_.field::text like '%"+ fieldVal+"%'"));
sherif
  • 2,282
  • 19
  • 21
0

for Integer search parameter

criteria = session.createCriteria(demo.class).add(Restrictions.sqlRestriction("sequenceNo LIKE '%"+searchParameter+"%' "));

Try this...

0
yourDetachedCriteriaObj.add(Restrictions.sqlRestriction(" sequenceNo LIKE '%"+yourSequenceNumToSearch+"%' "));

return error for unabling type cast:

operator does not exit : integer ~~ unknown HINT: No operator matches the given name and argument tyeps(s). you might need to add explicitr type casts.

so, we can use this code:

yourDetachedCriteriaObj.add(Restrictions.sqlRestriction(" sequenceNo ::text LIKE '%"+yourSequenceNumToSearch+"%' "));
M2E67
  • 937
  • 7
  • 23