Zut*_*tty 5 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...
}
Run Code Online (Sandbox Code Playgroud)
运行它会产生异常,因为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
Run Code Online (Sandbox Code Playgroud)
它可以工作,如果我count改为a Long但我宁愿不更改视图模型类,因为它使用的是其他各种地方.
我可以Projections.count()以Integer某种方式返回或使结果转换器转换Long为Integer?
您可以使用 SQL 投影将其转换为 Integer:
.setProjection( Projections.sqlProjection(
"Cast(Count(foo) as Integer) count",
new String[]{"count"},
new Type[]{StandardBasicTypes.INTEGER}
)
Run Code Online (Sandbox Code Playgroud)