Warm tip: This article is reproduced from serverfault.com, please click

Hibernate count with Restrictions.in with list of Enum objects

发布于 2020-11-27 17:54:13

I am using Hibernate 5.4.18.Final. I have a valid @Entity Appointment which has property status which is a Enum of my custom type AppointmentStatus which is mapped using @Enumerated( EnumType.STRING ). Also I have a DAO which has a method count() that is counting rows by given Criteria like this:

    @Override
    public <T> Long countRows( Class<T> clazz, List<FilterElement> filter ) {
        Criteria criteria = buildCriteria( clazz, filter );
        criteria.setProjection( Projections.rowCount() );
        return (long) criteria.uniqueResult();
    }

buildCriteria() method looks like this:

    @Override
    private <T> Criteria buildCriteria( Class<T> clazz, List<FilterElement> filter ) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria( clazz );

        for ( FilterElement element : filter ) {
            
            //taking care of different types of operations
            //...

            //if IN operation is required
            if ( element.getOperation() == FilterElement.FilterOperations.IN && element.getValue() instanceof List ) {
                criteria.add( Restrictions.in( element.getProperty(), element.getValue() ) );
            }
        }

        return criteria;
    }

So the whole purpose of this is that I could select (and in this instance - count) all the records that have any of the AppointmentStatus statuses passed in filter.getValue() which is a List<Enum>. But instead of expected result I get this exception: class java.util.ArrayList cannot be cast to class java.lang.Enum which happens when criteria.uniqueResult() is called.

What am I doing wrong? Thanks in advance.

Questioner
Pavel Polyakoff
Viewed
0
Pavel Polyakoff 2020-12-01 22:33:45

I solved it. Just transformed List to Array.