简体   繁体   English

Hibernate 标准、整数和“喜欢”

[英]Hibernate Criteria, Integer and "like"

I'm migrating some of my hql-statements to Criterias now I'm figuring one problem: The entity property is type Integer but I need a like with wildcards search, so in hql I do我正在将我的一些 hql 语句迁移到 Criterias 现在我正在解决一个问题:实体属性是 Integer 类型,但我需要通配符搜索,所以在 hql 中我做

session.createQuery("from P1 where id like :id").setString("id", "%"+s+"%")

No problem at all, Hibernate casts String to Integer.完全没问题,Hibernate 将 String 转换为 Integer。

If I try this in Criteria, I only get a ClassCastException如果我在 Criteria 中尝试这个,我只会得到一个 ClassCastException

String cannot be cast to Integer

Criteria crit = sessionFactory.getCurrentSession().createCriteria(P1.class);
crit.add(Restrictions.like("id",s)).addOrder(Order.asc("id")).setMaxResults(maxResults);

Why does Hibernate handle both situations differently?为什么 Hibernate 对这两种情况的处理方式不同?

You could use the str expression conversion .您可以使用str 表达式转换 If this makes any sense.如果这有任何意义。

str() for converting numeric or temporal values to a readable string str() 用于将数字或时间值转换为可读字符串

session.createQuery("from P1 where str(id) like :id").setString("id", "%"+s+"%")

This will be quite slow if you do not have a function based index on the column.如果列上没有基于函数的索引,这将非常慢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM