使用Result Transformer计算Hibernate 4.1 Count Projection Type Mismatch(Long / Integer)

时间:2013-05-23 11:37:46

标签: java hibernate criteria

我有一个实体bean FooEntity和DAO方法来获取按该实体上的属性分组的行计数,封装在视图模型bean FooCount中。

public List<FooCount> groupByFoo() {
    return sessionFactory.getCurrentSession()
        .createCriteria(FooEntity.class)
        .setProjection(Projections.projectionList()
            .add(Projections.groupProperty("foo"), "foo")
            .add(Projections.count("foo"), "count")
        ).setResultTransformer(Transformers.aliasToBean(FooCount.class))  
        .list();
}

public class FooCount {
    private String foo;
    private Integer count; // <-- this is the problem
    // getters/setters...
}

运行此操作会产生异常,因为Projections.count()会产生Long而不是Integer

org.hibernate.PropertyAccessException: IllegalArgumentException occurred while calling setter of FooCount.count
    at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:119)
--snip--
    Caused by: java.lang.IllegalArgumentException: argument type mismatch

如果我将count更改为Long,但我不想更改视图模型类,因为它使用的是其他各种地方。

我可以让Projections.count()以某种方式返回Integer 使结果转换器从Long转换为Integer吗?

3 个答案:

答案 0 :(得分:4)

您可以使用SQL投影将其强制转换为Integer:

.setProjection( Projections.sqlProjection(
    "Cast(Count(foo) as Integer) count",
    new String[]{"count"},
    new Type[]{StandardBasicTypes.INTEGER}
)

答案 1 :(得分:1)

你不能在属性的setter方法中自己进行转换吗?

答案 2 :(得分:0)

看起来Hibernate中COUNT(*)函数的标准映射是BigDecimal。因此,替换Integer可以提供帮助:

public class FooCount {
  private String foo;
  private BigDecimal count; // <-- 

  // getters/setters...
}
相关问题