Compile error when using CriteriaBuilder

后端 未结 3 1923
-上瘾入骨i
-上瘾入骨i 2021-01-19 10:13

I am trying convert this JPA QL to criteria builder. JBoss 6.0.

\"SELECT ba FROM BankAccount ba WHERE ba.balance >= :amt ORDER BY ba.ownerName ASC\"
         


        
3条回答
  •  天命终不由人
    2021-01-19 10:49

    The type safety feature in JPA restricts such comparisons with incompatible types, the compiler itself will raise error.

    Here, from.get("balance") returns the Path, but the method can accept parameter of type java.lang.Number, therefore results in error.

    You can try the below code.

    //--
        Metamodel metamodel = em.getMetamodel();
        EntityType pClass = metamodel.entity(BankAccount.class);
        Predicate predicate = cb.gt(from.get(pClass.getSingularAttribute("balance", Integer.class)), balance);
    //--
    

    If you are using Metamodel API, then you can retieve directly by specifying ClassName_.field as cb.gt(from.get(BankAccount_.balance), balance) which is much cleaner & easy to debug.

    But if you are having many entities, then it may be difficult to write their Metamodel classes manually, if the JPA provider doesn't generate them.

    提交回复
    热议问题