JPA: query for all items in a list where target is also a list
I have two entities:
Engineer - has a set of tags (say skillsets - Java. .NET, etc.)
Tag
An engineer may have any number of tags. And a tag is associated with any
number of engineers.
@Entity
public class Engineer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(nullable = false, length = 12)
private String id;
@Column(length = 100)
private String name;
@OneToMany(fetch = FetchType.EAGER)
List<Tag> tags;
/* Getters and Setters */
}
@Entity
public class Tag implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int id;
@Column(length = 50)
private String name;
/* Getters and Setters */
}
Now, I want to query for engineers who have a list of tags associated with
them. For example - "Query for engineers with tags 'Java', 'Opensource',
and 'Banking'". The query should return engineers who have all the tags
associated with them.
I am able to query for one tag:
public List<Engineer> searchMindsByTags(String tag) {
Query q = em.createQuery("SELECT e FROM Engineer e WHERE '" + tag
+ "' = ANY(SELECT tag.name FROM e.tags tag)");
return (List<Engineer>) q.getResultList();
}
What I need is:
public List<Engineer> searchMindsByTags(List<String> tags) {
/* Which query goes here? */
}
Is there a single query which can do this job or do we need iterate over
the results progressively to filter?
No comments:
Post a Comment