简体   繁体   English

带有基本值集合的休眠条件查询

[英]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: 我是Hibernate的新手,尤其是Criteria API的新手,我找不到我的问题的答案。.这是简化的域类:

@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. 我需要一些条件来限制条件,即如果accepterCodes集合中存在某些值(字符串代码),这些条件将得到满足。

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 我在这里找到答案https://docs.jboss.org/hibernate/orm/4.3/manual/zh-CN/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"." “对于查询基本值的集合,我们仍然针对该集合创建Criteria对象,但是要引用该值, 我们使用特殊属性“ elements” 。对于索引集合,我们还可以使用special属性来引用index属性“指数”。”

Also, when creating alias your need to specify sql LEFT_JOIN (the default is INNER_JOIN) or you will not get expected result, probably. 另外,在创建别名时,您需要指定sql LEFT_JOIN(默认值为INNER_JOIN),否则可能无法获得预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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