Selecting an entity by collection set equality

99封情书 提交于 2019-12-24 00:55:47

问题


I'm trying to do a JPQL query or JPA operation that does the following. I have an element, that consist of an element collection of Strings:

@Entity(name="REQUEST")
public class Request {

    @ElementCollection
    private Set<String> keywords;
    ...    
}

I want to be able to select the entity whos keywords exactly matches a given Set of strings. I've looked into using IN but that will match if only one keyword exists. How do I match only if all keywords exist?


回答1:


The simplest approach I can think of is to do two count queries:

  1. A count of the number of keywords IN the set
  2. A count of the number of keywords NOT IN the set

The result of #1 should equal the number of keywords in the set. The result of #2 should equal 0. For example:

List<Request> requests = 
  em.createQuery("select r from Request r " +
                 "where (select count(k1) from Request r1 " +
                 "       join r1.keywords k1 " +
                 "       where r1 = r and k1 in :keywords) = :numKeywords " +
                 "and (select count(k2) from Request r2 " +
                 "     join r2.keywords k2 " +
                 "     where r2 = r and k2 not in :keywords) = 0", Request.class)
     .setParameter("keywords", keywords)
     .setParameter("numKeywords", keywords.size())
     .getResultList();

If all you cared about was whether or not the set is a subset of the Request's keywords, then the second count is not needed. This can be done in a single query with a group by:

List<Request> requests = 
      em.createQuery("select r from Request r " +
                     "join r.keywords k " +
                     "where k in :keywords " +
                     "group by r " +
                     "having count(r) = :numKeywords", Request.class)
        .setParameter("keywords", keywords)
        .setParameter("numKeywords", keywords.size())
        .getResultList();


来源:https://stackoverflow.com/questions/22291993/selecting-an-entity-by-collection-set-equality

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!