WelcomeTo
WelcomeTo

Reputation: 20581

Querying over the content of an @ElementCollection. Hibernate Criteria way

I have an entity which contains @ElementCollectionfield with enums.

public enum StatusType { 
    NEW, PENDING, CLOSED;
}

@Entity
public class MyEntity {
    @ElementCollection
    @CollectionTable(name = "status_type", joinColumns = {@JoinColumn(name = "my_entity_id")}) 
    @Column(name = "status_type", nullable = false)
    private Set<StatusType > statusTypes = new HashSet<StatusType >();

    ...
}

Now I want to get all entities which contains status NEW or PENDING (or both).

I.e.

Criteria criteria = session().createCriteria( MyEntity.class );
List<StatusType > statuses = new ArrayList()<>;
statuses.add(StatusType.NEW);
statuses.add(StatusType.PENDING);

criteria.createAlias( "statusTypes", "statusTypes" );
criteria.add( Restrictions.in( "statusTypes", statuses) );

This code doesn't work :

Caused by: org.hibernate.MappingException: collection was not an association: com.blabla.MyEntity.statusTypes

So, How I can get all MyEnitity which are have inside statusTypes field NEW or PENDING values (or both)

Also, please not, that I don't want to use HQL because I need to support optional parameters. So I need dynamically add restrictions if parameters are not null or not empty.

Upvotes: 2

Views: 1286

Answers (1)

Floris Kruisselbrink
Floris Kruisselbrink

Reputation: 31

I know this is a pretty old question, but there is a very basic mistake here and no one has spotted it.

You need to change the last two lines to:

criteria.createAlias( "statusTypes", "statusTypes" );
criteria.add( Restrictions.in( "statusTypes.elements", statuses) );

Think of statustypes as its own database-table (it actually is). To query it, you need to join it (createAlias), and then query on a property of the joined table. In your example you are trying to query on the joined table itself.

As this is not a table with its own entity-mapping, but an ElementCollection, the column you need to query is the special phrase 'elements'.

Upvotes: 3

Related Questions