Search code examples
javadatabasehibernatecriteria

Hibernate criteria query with collection of basic values


I am newbie in Hibernate especially in Criteria API and I can't find answer on my question.. Here is simplified domain class:

@Entity
public class HDNewsPost implements Serializable {
    @Id
    private Long id;

    //other fields
    //..    

    @ElementCollection
    @CollectionTable(name = "SD_SOLUTION.PBITSM_HD_NEWS_RECIPIENT_CODES",
            joinColumns = @JoinColumn(name = "POST_ID"))
    @Column(name="POSITION_CODE")
    private List<String> recipientCodes;

    //getters and setters
}

I need restriction for criteria that will satisfy if some value (String code) is present in recipientCodes collection.


Solution

  • I solved my task! Here is full criteria query with part where I have a problem:

    final Criteria criteria = sessionFactory.getCurrentSession().createCriteria(HDNewsPost.class);
    criteria.setFirstResult(startFrom);
    criteria.setMaxResults(maxResults);
    criteria.addOrder(Order.desc("publicationDate"));
    
    if (code != null) {
        criteria.createAlias("recipientCodes", "rc", CriteriaSpecification.LEFT_JOIN);
        criteria.add(Restrictions.or(Restrictions.isEmpty("recipientCodes"),
            Restrictions.eq("rc.elements", code)));
    }
    
    return criteria.list();
    

    I have found answer here https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch17.html#querycriteria-collections

    "For queryng a collection of basic values, we still create the Criteria object against the collection, but to reference the value, we use the special property "elements". For an indexed collection, we can also reference the index property using the special property "indices"."

    Also, when creating alias your need to specify sql LEFT_JOIN (the default is INNER_JOIN) or you will not get expected result, probably.