[英]How to compare using HIbernate criteria on a string column treating it as a long column
I am working on a web project written in java that uses Hibernate for data access from a oracle database. 我正在使用Java编写的Web项目,该项目使用Hibernate从oracle数据库进行数据访问。
I have a column name serial
in my database which is defined as VARCHAR(12)
even though it contains only values that can be cast into long
. 我的数据库中有一个列名称serial
,该列名称定义为VARCHAR(12)
即使它只包含可以转换为long
。 My intention is get all serials (treating them as numbers) between numbers fromNo
and toNo
. 我的意图是获取从fromNo
到toNo
之间的所有序列号(将它们作为数字进行处理)。 I cannot use Restrictions.between
because the serial
column is not a number in DB. 我不能使用Restrictions.between
因为serial
列不是DB中的数字。 It is defined as String
in the associated object as well. 在关联对象中也将其定义为String
。 Right now I achieve the requirement (in an ugly way) by converting the number range to a list of strings and do a Restricitons.in
on the column. 现在,我通过将数字范围转换为字符串列表并在该列上执行Restricitons.in
(以丑陋的方式)来达到要求。
long fromNO = 10;
long toNo = 100;
List<String> listNos = null;
for (long k = fromNo; k <=toNO; k++) {
listNos.add(k.toString());
}
Criteria criteria = getMyHibernateSession().createCriteria(MyObject.class);
criteria.add(Restrictions.in('serialNo',listNos));
List<MyObject> results = criteria.list();
Though I get the desired results, the problem happens when the toNo
is not defined by the user and the tool need to get all the serial
from fromNo
虽然我得到了预期的结果,但是当用户未定义toNo
且工具需要从fromNo
获取所有serial
, fromNo
My question is how can write a hibernate criteria where I can overcome all this problem, by specifying Criteria to treat serial
column as long
and not String
? 我的问题是,如何通过指定Criteria将serial
列视为long
而不是String
来编写休眠标准,从而克服所有这些问题? (Some sort of casting process may be?) (可能是某种铸造过程?)
You can add new 'long' field in your entity annotated as 您可以在实体中添加新的“长”字段,其注释为
@Formula("cast(serialNo as NUMBER(10,0))")
private int lSerialNo;
Then use the new field lSerialNo
in your Restrictions
然后在您的Restrictions
使用新字段lSerialNo
Please try to use Restrictions.between. 请尝试使用Restrictions.between。 Try to parse the integer to string 尝试将整数解析为字符串
criteria.add(Restrictions.between('serialNo',String.valueOf(listNosFrom),String.valueOf(listNosTo)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.