Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 289
kwan_ah Avatar asked Mar 20 '13 03:03

kwan_ah


People also ask

What is detached criteria in Hibernate?

The detached criteria allows you to create the query without Session . Then you can execute the search in an arbitrary session. In fact you should think carefully when using a detached criteria using another, or a new, session (no cache, and creation of the session).

How do you put restrictions in criteria query?

Restrictions with CriteriaCriteria cr = session. createCriteria(Employee. class); Criterion salary = Restrictions.gt("salary", 2000); Criterion name = Restrictions. ilike("firstNname","zara%"); // To get records matching with OR conditions LogicalExpression orExp = Restrictions.or(salary, name); cr.

How to use Join in Criteria in Hibernate?

Criteria in Hibernate can be used for join queries by joining multiple tables, useful methods for Hibernate criteria join are createAlias(), setFetchMode() and setProjection() Criteria in Hibernate API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.

What is the use of createAlias in Hibernate?

createAlias. Join an association using the specified join-type, assigning an alias to the joined association. The joinType is expected to be one of CriteriaSpecification.


1 Answers

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.
like image 59
maimoona Avatar answered Oct 14 '22 08:10

maimoona