我有一个实体bean FooEntity和DAO方法来获取按该实体上的属性分组的行计数,这些行计数封装在 View 模型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,它会起作用,但是我不希望不更改 View 模型类,因为它在其他各种地方都被使用。

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

最佳答案

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

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

关于java - 使用Result Transformer的Hibernate 4.1计数投影类型不匹配(长/整数),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16712940/

10-16 05:25