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}
)
Can't you do the conversion yourself in the attribute's setter method?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With