Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate 4.1 Count Projection Type Mismatch (Long/Integer) using Result Transformer

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?

like image 461
Zutty Avatar asked May 23 '13 11:05

Zutty


2 Answers

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}
)
like image 51
Ziul Avatar answered Oct 17 '22 06:10

Ziul


Can't you do the conversion yourself in the attribute's setter method?

like image 1
Eduardo Bueno Avatar answered Oct 17 '22 05:10

Eduardo Bueno