Criterion Restrictions.like 以及数字和日期

发布于 2024-11-10 01:41:49 字数 284 浏览 3 评论 0原文

我使用 Hibernate 而不是 mySQL。在 mySQL 中,您甚至可以在查询中放入 LIKE ,甚至可以对数字(如双精度)参数和日期进行查询,例如您可以编写:

select * from sillytable where field like "3.33%"

这将起作用。问题是我不能使用 Restrictions.like 在标准中执行此操作,事实上它会抛出一个异常,表示它无法将 String 转换为 Date 或 Double。

我怎样才能用它做到这一点?

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 this with it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

不羁少年 2024-11-17 01:41:49

我发现唯一好的解决方案可以实现我想要做的事情就是使用 HQL。
Criteria 中没有明确的方法来做到这一点

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

浮世清欢 2024-11-17 01:41:49

我认为这实际上是:

x => 3.33 and x < 3.34

在休眠中这是:

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

Between 定义为 (min <= expr AND expr <= max)。因此上限必须更改为从 3.33 开始的最大值。 (警告:如果上限不可表示并且 3.34 用 3.33999... 表示,则表示可能会失败。如果您使用这个已经有效的边界执行 nextAfter,您将错过这个值。)

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

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));
半葬歌 2024-11-17 01:41:49
Criteria crit;

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

try {
  crit = session.createCriteria(sillytable.class, "st");
  crit.add(Restrictions.like("field", number + "%"));
}
小清晰的声音 2024-11-17 01:41:49

如果您仍然想坚持 Hibernate 标准,请使用 Restrictions.sqlRestriction 而不是 Restrictions.like,如下所述:

Restrictions.sqlRestriction(" CAST({alias}.field AS CHAR) LIKE ('%" + 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 + "%')")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文