本文介绍了如何查询与JPA2的M:N关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何查询一个对象(BlogPost)在哪里至少有一个它的标签与JPA2(Hibernate)中的一组标签(由用户定义)匹配元素。
findBlogPostWithAtLeastOneMatchingTag (收集< Tag>标签){???? }
我的主要问题是,我实际上需要比较两个标记集合:
- BlogPost的标签集合。
- 我搜索的集合
我试过从Post p中选择p,其中p.tags在(:tags)
但它不起作用,因为我的帖子实体不只有一个标签。
那么我可以做些什么呢?
我的BlogPost实体看起来像这样。它有几个标签。
@Entity
公共类BlogPost {
/ **标签。 * /
@ManyToMany()
@NotNull
私人设置< Tag>标签;
@NotBlank
私人字符串内容;
...
}
解决方案不能是JPQL,JPA-Criteria(不是Hibernate-Criteria)也可以。 解决方案
p>如果你喜欢JPA Criteria,这是你的解决方案:
List< Integer> myTagsIds = new ArrayList< Integer> ();
myTagsIds.add(1);
myTagsIds.add(2);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery< BlogPost> cq = cb.createQuery(BlogPost.class);
Root< BlogPost> blogPost = cq.from(BlogPost.class);
SetJoin< BlogPost,Tag> tags = blogPost.join(BlogPost_.tags);
Predicate predicate = tags.get(Tag_.id).in(myTagsIds);
cq.distinct(true);
cq.where(predicate);
TypedQuery< BlogPost> tq = em.createQuery(cq);
return tq.getResultList();
这个解决方案利用类 BlogPost _
和标记_
应该由您的JPA实现生成。
I have an an object (BlogPost) that contains an M:N collection of elements (Tags).
How to query for an object (BlogPost) where at least one it its Tags matches an element in a set of Tags (defined by the user) with JPA2 (Hibernate).
findBlogPostWithAtLeastOneMatchingTag(Collection<Tag> tags){ ???? }
My main problem is, that I actually need to compare two collections of tags:- the collection of tags of the BlogPost.- the collection I search for
I tried Select p from Post p where p.tags in(:tags)
but it does not work, as my post entities have more than just one tag.
So what could I do instead?
My BlogPost entity looks like this. It has several Tags.
@Entity
public class BlogPost{
/** The tags. */
@ManyToMany()
@NotNull
private Set<Tag> tags;
@NotBlank
private String content;
...
}
The solution must not be JPQL, JPA-Criteria (not Hibernate-Criteria) would be fine too.
解决方案
If you like JPA Criteria, this is the solution for you:
List<Integer> myTagsIds = new ArrayList<Integer> ();
myTagsIds.add(1);
myTagsIds.add(2);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<BlogPost> cq = cb.createQuery(BlogPost.class);
Root<BlogPost> blogPost = cq.from(BlogPost.class);
SetJoin<BlogPost, Tag> tags = blogPost.join(BlogPost_.tags);
Predicate predicate = tags.get(Tag_.id).in(myTagsIds);
cq.distinct(true);
cq.where(predicate);
TypedQuery<BlogPost> tq = em.createQuery(cq);
return tq.getResultList();
This solution makes use of the canonical MetaModel classes BlogPost_
and Tag_
that should be generated by your JPA implementation.
这篇关于如何查询与JPA2的M:N关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!