HQL查询从多个Item对象实例中检索公共标记

时间:2011-06-19 20:30:51

标签: java sql hql

让我们说我有一个查询,它带有以下列表项目对象:#/ p>

Item1{TagSet{tag1,tag2,tag3}}
Item2{TagSet{tag3,tag4,tag5}}
Item3{TagSet{tag6,tag7,tag8}}

Item1 Item2 Item3 are instances of Item object in List 
TagSet is Set Collection object

哪些HQL或SQL查询将检索List of Items having tag3并从该结果get list of all tags from thouse items that contain tag3not including tag3)中检索,例如。从上面的3个项目?

期望的结果将是:

TagSet{tag1, tag2, tag4, tag5}

1 个答案:

答案 0 :(得分:1)

你没有给我们你的架构,所以我猜这里,但是......

SQL:

select distinct *
from item
join tag on tag.item_id = item.id
where item.name = 'foo'
and tag.name != 'tag3'
and item.id in (select item_id from tag where name = 'tag3');

HQL:

entityManager
.createQuery("
    select t
    from Tag t
    where t.name != 'tag3'
    and t.item in (select t2.item from Tag t2 where t2.name = 'Tag3')
    and t.item.name = :name")
.setParateter("name", "foo")
.getResultList();

然后使用tag.getItem()获取返回标签的Items。