Hibernate Criteria,Integer和“like” [英] Hibernate Criteria, Integer and "like"
问题描述
我正在将一些hql语句迁移到Criterias现在我正在计算一个问题:
实体属性是Integer类型,但我需要一个类似于通配符搜索的方法,所以在hql中
session.createQuery(from P1 where id:id)。setString(id,%+ s +% )
完全没问题,Hibernate将字符串转换为整型。
如果我在Criteria中尝试这样做,我只会得到一个ClassCastException
字符串不能转换为Integer
Criteria crit = sessionFactory.getCurrentSession()。createCriteria(P1.class);
crit.add(Restrictions.like(id,s))。addOrder(Order.asc(id))。setMaxResults(maxResults);
为什么Hibernate会以不同的方式处理两种情况?
您可以使用 str表达式转换。如果这是有道理的。
lockquote
str()用于将数值或
时间值转换为可读的字符串$ / $
$ $ p $ session.createQuery(from P1 where str(id)like:id)。setString(id ,%+ s +%)
如果您没有基于功能的索引。
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
session.createQuery("from P1 where id like :id").setString("id", "%"+s+"%")
No problem at all, Hibernate casts String to Integer.
If I try this in Criteria, I only get a 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?
You could use the str expression conversion. If this makes any sense.
str() for converting numeric or temporal values to a readable string
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.
这篇关于Hibernate Criteria,Integer和“like”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!