Hibernate 4.1使用Result Transformer计算投影类型不匹配(长/整数) [英] Hibernate 4.1 Count Projection Type Mismatch (Long/Integer) using Result Transformer

查看:108
本文介绍了Hibernate 4.1使用Result Transformer计算投影类型不匹配(长/整数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体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 ();
}

公共类FooCount {
private String foo;
私人整数计数; //< - 这是问题
// getters / setters ...
}


$因为 Projections.count()会产生一个 Long 而不是整数

  org.hibernate.PropertyAccessException:调用setter时发生IllegalArgumentException FooCount.count 
at org.hibernate.property.BasicPropertyAccessor $ BasicSetter.set(BasicPropertyAccessor.java:119)
--snip--
引起:java.lang.IllegalArgumentException:argument类型不匹配

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



我可以使 Projections.count()返回一个整数以某种方式结果转换器从 Long 转换为整数

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

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


I have an entity bean FooEntity and DAO method to get row counts grouped by a property on that entity, encapsulated in a view model 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...
}

Running this gives an exception, since Projections.count() yields a Long instead of an 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

It works if I change count to a Long but I would prefer not to change the view model class as it is used is various other places.

Can I either make Projections.count() return an Integer somehow or make the result transformer convert from Long to Integer?

解决方案

You can cast it to Integer using a SQL projection:

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

这篇关于Hibernate 4.1使用Result Transformer计算投影类型不匹配(长/整数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆