简体   繁体   中英

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

I have an entity which contains @ElementCollection field 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).

Ie

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM