Hibernate 4.1 Count Projection type mismatch (long / integer) using result transformer

I have a bean FooEntity object and a DAO method to get the count of rows grouped by a property on this object enclosed in a bean FooCount view model.

 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... } 

Doing this throws an exception, since Projections.count() gives Long instead of 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 Long , but I would prefer not to change the class of the view model, as it is used elsewhere.

Is it possible to either make Projections.count() return a Integer some way, or to convert the result transformer from Long to Integer ?

+4
source share
3 answers

You can pass it to Integer using SQL prediction:

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

Can you do the conversion yourself in the attribute setting method?

+1
source

It looks like the standard mapping of the COUNT (*) function in Hibernate BigDecimal . Therefore, replacing Integer can help:

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

Source: https://habr.com/ru/post/1482365/


All Articles