【问题标题】:Hibernate 4.1 Count Projection Type Mismatch (Long/Integer) using Result TransformerHibernate 4.1 Count Projection Type Mismatch (Long/Integer) using Result Transformer
【发布时间】:2013-05-18 18:06:42
【问题描述】:

我有一个实体 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

【问题讨论】:

    标签: java hibernate criteria


    【解决方案1】:

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

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

    【讨论】:

    • 啊,太棒了。这也比我当前的解决方案好得多,因为我的实际代码比我发布的 SSCCE 更复杂,这让我可以进一步简化。谢谢。
    【解决方案2】:

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

    【讨论】:

    • 我确实尝试过这个,但希望有一种不涉及更改 FooCount bean 的方法
    【解决方案3】:

    看起来 Hibernate 中 COUNT(*) 函数的标准映射是BigDecimal。所以替换 Integer 会有所帮助:

    public class FooCount {
      private String foo;
      private BigDecimal count; // <-- 
    
      // getters/setters...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-07
      • 2013-09-30
      • 2010-10-16
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多