问题
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
?
回答1:
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}
)
回答2:
Can't you do the conversion yourself in the attribute's setter method?
回答3:
It looks like the standard mapping for COUNT(*) function in Hibernate is BigDecimal. So replacing of Integer can help:
public class FooCount {
private String foo;
private BigDecimal count; // <--
// getters/setters...
}
来源:https://stackoverflow.com/questions/16712940/hibernate-4-1-count-projection-type-mismatch-long-integer-using-result-transfo