简体   繁体   English

Hibernate 5无法将字符串与int进行比较

[英]Hibernate 5 can't compare string with int

I migrate hibernate from version 4.3.7 to 5.3.7 Currently my code goes like this 我将休眠从版本4.3.7迁移到了5.3.7目前我的代码是这样的

public BcData findByBcCode(int clearingNumber) {
        CriteriaBuilder cb = getCriteriaBuilder();
        CriteriaQuery<BcData> query = cb.createQuery(BcData.class);
        Root<BcData> bcAlias = query.from(BcData.class);
        query.where(cb.equal(bcAlias.get(BcData_.bcCode), clearingNumber));
        return findSingle(query, new HashMap<>());
    }

So in DB, bcCode has type String , values 00437 , 22437 and clearingNumber = 437. 因此,在DB, bcCode的类型是String ,值0043722437和clearingNumber = 437。

In hibernate version 4.x , it can get result with bcCode = 00437 . 在休眠版本4.x ,可以使用bcCode = 00437获得结果。

In version 5.x , result is null unless the input is clearingNumber = 00437 在版本5.x ,除非输入为clearingNumber = 00437否则结果为null。

So question is that how can I get result same as version 4 without changing param type (int clearingNumber) . 所以问题是,如何在不更改参数类型(int clearingNumber)情况下获得与版本4相同的结果。

Thanks. 谢谢。 Update 1: Inside method equal, it takes input param as object, so generally it can compare many type of input parameters 更新1:内部方法相等,它以输入参数为对象,因此通常可以比较多种类型的输入参数

@Override
    @SuppressWarnings("SuspiciousNameCombination")
    public Predicate equal(Expression<?> x, Object y) {
        return new ComparisonPredicate( this, ComparisonOperator.EQUAL, x, y );
    }

Update 2: finally I found a solution for this, we should parse bcCode as int before querying 更新2:终于我找到了解决方案,我们应该在查询之前将bcCode解析为int

Expression<Integer> bcCodeExpr = bcAlias.get(BcData_.bcCode).as(Integer.class);
query.where(cb.equal(bcCodeExpr, clearingNumber));

It should have not worked in the beginning. 一开始它不应该起作用。 You probably hot lucky with how your string was casted into an integer. 您可能对将字符串转换为整数很幸运。

It is not very smart to compare String with int. 将String与int进行比较不是很聪明。 I would convert the string into an int by hand and then compare them. 我会手动将字符串转换为int,然后进行比较。 Or you need to somehow delete all trailing spaces in bcCode and then compare them as string with string. 或者,您需要以某种方式删除bcCode中的所有尾随空格,然后将它们作为字符串与字符串进行比较。

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

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