= :amt ORDER BY-6ren">
gpt4 book ai didi

java - 使用 CriteriaBuilder 时编译错误

转载 作者:搜寻专家 更新时间:2023-11-01 01:11:02 26 4
gpt4 key购买 nike

我正在尝试将此 JPA QL 转换为条件生成器。 JBoss 6.0。

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

我根据几个教程编写了这段代码。

public List<BankAccount> findWithBalance(int amount) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<BankAccount> cq = cb.createQuery(BankAccount.class);
Root<BankAccount> from = cq.from(BankAccount.class);

ParameterExpression<Integer> balance = cb.parameter(Integer.class);
cq.select(from);

Predicate predicate = cb.gt(from.get("balance"), balance);
cq.where(predicate);

cq.orderBy(cb.asc(from.get("ownerName")));

TypedQuery<BankAccount> query = em.createQuery(cq);

return query.getResultList();
}

但是,我在行中遇到编译错误:

Predicate predicate = cb.gt(from.get("balance"), balance);

错误是:

The method gt(Expression<? extends Number>, Expression<? extends Number>) in the type CriteriaBuilder is not applicable for the arguments (Path<Object>, ParameterExpression<Integer>)

最佳答案

好吧,我终于找到了调用 gt() 方法的正确方法。这是完整的解决方案。在 JBoss 6 中经过全面测试。

public List<BankAccount> findWithBalance(int amount) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<BankAccount> cq = cb.createQuery(BankAccount.class);
Root<BankAccount> from = cq.from(BankAccount.class);

ParameterExpression<Integer> balance = cb.parameter(Integer.class);
cq.select(from);

//Here is the trick!
Predicate predicate = cb.gt(from.<Integer> get("balance"), balance);

cq.where(predicate);
cq.orderBy(cb.asc(from.get("ownerName")));

TypedQuery<BankAccount> query = em.createQuery(cq);

query.setParameter(balance, amount);

return query.getResultList();
}

关于java - 使用 CriteriaBuilder 时编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10390115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com