开发者

Criterion Restrictions.like and numbers and dates

开发者 https://www.devze.com 2023-03-08 14:28 出处:网络
I\'m using Hibernate over mySQL. In mySQL you can put LIKE in queries even on number (like double) parameters and dates, for example you can write:

I'm using Hibernate over mySQL. In mySQL you can put LIKE in queries even on number (like double) parameters and dates, for example you can write:

select * from sillytable where field like "3.33%"

and this will work. The problem is that I can't do this in criterion using Restrictions.like, in fact it throws an exception says that it can't cast a String to a Date or Double.

How can I do t开发者_开发百科his with it?


I found that the only good solution that did what I meant to do was using HQL. There is no clear way to do this in Criteria


I think this is actually:

x => 3.33 and x < 3.34

In hibernate this is:

Restriction.between("field", 3.33, 3.34)

Between is defined as (min <= expr AND expr <= max). So the upper bound has to be changed to the biggest value starting with 3.33. (Caveat: You could have a representation failure if the upper bound is not representable and 3.34 is representated with 3.33999... . You would miss this one value if you do nextAfter with this already valid bound.)

Restriction.between("field", 3.33, Math.nextAfter(3.34, -Double.MAX_VALUE));


Criteria crit;

try {
  crit = session.createCriteria(sillytable.class, "st");
  crit.add(Restrictions.like("field", number + "%"));
}


If you still want to stick to Hibernate criteria use Restrictions.sqlRestriction instead of Restrictions.like as explained below:

Restrictions.sqlRestriction(" CAST({alias}.field AS CHAR) LIKE ('%" + number + "%')")
0

精彩评论

暂无评论...
验证码 换一张
取 消