【问题标题】:How can I use JPA do this SQL query?如何使用 JPA 执行此 SQL 查询?
【发布时间】:2021-02-15 21:13:45
【问题描述】:

大家好,我尝试在 JPA 中执行此查询 "SELECT SUM(cevecoin) FROM coin where clid="ABC" 但它不起作用。有人可以帮帮我吗?

public Integer SumCoin(String Clid) {
    CriteriaBuilder builder =getSession().getCriteriaBuilder();
    CriteriaQuery<CoinBean> criteria =builder.createQuery(CoinBean.class);
    Root<CoinBean> root = criteria.from(CoinBean.class);
    criteria.select(builder.sum(root.<Integer>get("clid")).as(CoinBean.class)).where(builder.equal(root.get("clid"),Clid));
    return getSession().createQuery(criteria).getSingleResult().getCevecoin();
}

【问题讨论】:

    标签: java sql jpa criteria


    【解决方案1】:

    试试这个:

    CriteriaBuilder builder =getSession().getCriteriaBuilder();
    // the type of query criteria must correspond to the result we want to obtain
    CriteriaQuery<BigDecimal> criteria = builder.createQuery(BigDecimal.class);
    Root<CoinBean> root = criteria.from(CoinBean.class);
    // use multiselect and sum the field cevecoin
    criteria.multiselect(builder.sum(root.get("cevecoin")))
    criteria.where(builder.equal(root.get("clid"),Clid));
    
    return getSession().createQuery(criteria).getSingleResult();
    

    【讨论】:

    • 它的工作想了很多。我的方法使用 Integer,所以我将 BigDecimal 更改为 Integer。感谢您的小心,发现应该使用“cevecoin”!谢了。
    • 最后它是一个近似值,费率可能会有所不同。我建议使用元模型来访问实体的属性,这样可以最大限度地减少构造查询时出错的可能性,因为您可以在开发环境中使用自动完成功能,而不是将属性作为容易出错的字符串。跨度>
    猜你喜欢
    • 2013-05-15
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多