如何使用findByNamedParam获取聚合值的对象?

时间:2012-11-29 03:28:28

标签: spring hibernate

我试图通过实际使用另一个对象的hibernate查询来获取count(*)和sum()的对象。这就是我正在做的事情:

String query = select new org.rangde.domain.AggregatedCount(count(*), sum(lps.loanAmount - lps.loanPledged - lps.loanRaised)) from LoanProfileSnapshot lps where  lps.loanState in (:loanStates) 
List<AggregatedCount> counts = getHibernateTemplate().findByNamedParam(query, params, values);
return counts.size() > 0 ? counts.get(0) : null;

这是AggregatedCount类(删除了getter和setter)

public class AggregatedCount {
    private int id;
    private BigInteger count;
    private BigDecimal sum;

    public AggregatedCount(){}

    public AggregatedCount(BigInteger count, BigDecimal sum){
        this.count = count;
        this.setSum(sum);
    }
}

这是我运行查询时遇到的异常。

Unable to locate appropriate constructor on class [org.domain.AggregatedCount] ...  nested exception is org.hibernate.hql.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [org.domain.AggregatedCount] ... 

我尝试将总和作为Double和BigInteger,但我仍然得到相同的异常。

任何帮助将不胜感激。我更喜欢坚持使用findByNamedParam,因为在生成最终查询之前,我在代码中检查了很多条件。感谢。

1 个答案:

答案 0 :(得分:0)

虽然我的答案似乎有点太晚了,也许它会帮助别人.. 计数所需的数据类型为Long,而sum取决于实体中的数据类型。

它还取决于您使用的hibernate版本: https://community.jboss.org/wiki/HibernateCoreMigrationGuide35?_sscc=t

public class AggregatedCount {

private Long count;
private Long sum;


   public AggregatedCount(Long count, Long sum){
      this.count = count;
      this.setSum(sum);
   }

}