How to query the M: n relationship with JPA2?
I have an object (blogpost), which contains a collection of M: n elements (tags)
How to query an object (blogpost), in which the label of at least one object matches the element in a group of labels (defined by the user) and JPA2 (hibernate)
findBlogPostWithAtLeastOneMatchingTag(Collection<Tag> tags){ ???? }
My main problem is that I actually need to compare two tag sets: – the tag set of blogpost. – My search collection
I try to select P from post P, where p.tags is in (: Tags), but it doesn't work because my post entity has only one tag
What should I do?
My blogpost entity looks like this It has several labels
@Entity public class BlogPost{ /** The tags. */ @ManyToMany() @NotNull private Set<Tag> tags; @NotBlank private String content; ... }
The solution cannot be jpql or JPA criteria (not hibernate criteria)
Solution
If you like JPA criteria, this is your solution:
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 uses the canonical metamodel class blogpost that should be generated by the JPA implementation_ And tag_