Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA JPQL: select items when attribute of item (list/set) contains another item

Tags:

list

set

jpa

jpql

public class Document extends Model {
... 
@ManyToMany
public Set<User> accessors;
...
}

I want to select all Documents which accessors contain a certain user. I have just minimal experiences with SQL and no experiences with JPQL. So how to do that?

thanks in advance

like image 454
fea17e86 Avatar asked Dec 01 '11 10:12

fea17e86


2 Answers

SELECT d FROM Document AS d WHERE :user MEMBER OF d.accessors

Should be what you need, and it is simpler than joining tables. Just dont forget to use the user as a parameter instead of using its id:

query.setParameter("user", user);
like image 126
rhlobo Avatar answered Nov 19 '22 16:11

rhlobo


select distinct d from Document d inner join d.accessors a where a.id = :id

You should learn how SQL joins work, and then learn how to use joins in JPQL. That's essential. You'll find plenty of tutorials online. Google is your friend.

like image 26
JB Nizet Avatar answered Nov 19 '22 16:11

JB Nizet