kwan_ah kwan_ah - 1 year ago 161
Java Question

How to use LIKE in hibernate detached criteria for integer data type?

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

The field
is integer type but the
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.

Answer Source

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download