在JPA中获取查询交集?

时间:2008-12-31 16:14:51

标签: sql jpa

我有:“图像”1:许多“imageToTag”很多:1“标签”

我想发出一个查询,该查询将返回至少标签[a,b,c]的所有图片。我不清楚如何在JPQL中对此进行建模。我可以动态构建查询字符串,但这对性能和安全性有害。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

PSEUDO CODE:

SELECT * FROM IMAGES 
  INNER JOIN IMAGETAGS A
    ON IMAGE.ID = A.IMAGEID AND A.TAGID = 'A'
  INNER JOIN IMAGETAGS B
    ON IMAGE.ID = B.IMAGEID AND B.TAGID = 'B'
  INNER JOIN IMAGETAGS C
    ON IMAGE.ID = C.IMAGEID AND C.TAGID = 'C'

只是猜测,但JPQL中的等价物将是

Select img from Image img 
 JOIN img.tag ta 
 JOIN img.tag tb 
 JOIN img.tag tc 
  WHERE ta.description = 'A' and tb.description = 'B' and tc.description = 'C'

答案 1 :(得分:0)

这是jpa查询语言

Select img from Image img where img.tag.description in ('A','B','C');