在hql查询或条件中将字符串列强制转换为int

时间:2015-05-14 06:38:21

标签: java hibernate hql

任何人都可以指导我哪里出错了吗?它给出零结果,但在db值中存在,条件出现在下面的查询中。

  Str = QueryImpl(from ArcZipCodeRange where cast(fromZip as int) >='12345' and cast(toZip as int)<='12345')
        arcZipCodeRangeList = 0

3 个答案:

答案 0 :(得分:6)

您确定您的条件是否正确?

cast(fromZip as int) >='12345' and cast(toZip as int)<='12345')

将使用from&gt;提供所有结果12345和to&lt; 12345.

应该是其他方式: from&lt; 12345和to&gt; 12345?

答案 1 :(得分:2)

您正在将fromZiptoZip转换为int,然后将其与String进行比较。那是在惹麻烦。

在比较的两侧使用相同的数据类型。

同样@Fazovsky注意到,你的情况似乎是错误的。

答案 2 :(得分:2)

您可以轻松地通过Hibernate Criteria执行此操作。对于解决方案,您必须为这些创建自己的Hibernate Formula(fromZip和toZip)。以下必须是你的pojo映射。

@Column
private String fromZip;

@Formula(value="to_number(fromZip)")
private double newfromZip;

@Column
private String toZip;

@Formula(value="to_number(toZip)")
private double newtoZip;

以下是您选择的标准:

Criteria criteria = session.createCriteria(ArcZipCodeRange.class);
criteria.add(Restrictions.le("newfromZip", yourIntegerParameter));
criteria.add(Restrictions.ge("newtoZip", yourIntegerParameter));
List<ArcZipCodeRange> list = criteria.list();

我希望这会对你有所帮助。