简体   繁体   中英

JPQL subquery equality to parameter

How might I accomplish something like the following, in JPQL?

SELECT item
  FROM Item item
  WHERE (
    SELECT tag.name, tag.color
    FROM Tag tag
    WHERE tag.item = item
    ORDER BY tag.name, tag.color
  ) = :tags

where :tags is a list of pairs of strings (ordered by name and color), passed in as a parameter, via .getQuery().setParameter("tags", tags) .

The basic idea is to suppose I have a set of items, each of which have 0+ associated tags of a string and color, and I wish to find any items that have exactly a particular set of name/color tags.

I've tried using basically what's shown above, as a query, but I get the vague error The right expression is not a valid expression . It seems to have trouble with the subquery. Any ideas? I don't really care how similar the solution is to my template above, as long as it fulfills the basic idea (and the target tag set can be dynamically specified).

Ok, I think I've figured out a way of doing it, more or less.

It assumes/requires, however, that given an item X, any tag name can show up at most once on X. It might be possible to modify the approach to allow completely duplicate tags, but I didn't need that, so I haven't tried to figure it out.

SELECT item 
  FROM Item item 
  WHERE ( 
    SELECT COUNT(tag1) 
    FROM Tag tag1
    WHERE tag1.item = item 
    AND CONCAT(tag1.name, ',', tag1.color) IN :tags 
  ) = :tagCount 
  AND ( 
    SELECT COUNT(tag2) 
    FROM Tag tag2
    WHERE tag2.item = item 
  ) = :tagCount 
  AND ( 
    SELECT COUNT(DISTINCT tag3.name) 
    FROM Tag tag3 
    WHERE tag3.item = item 
  ) = :tagCount 

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