[英]JPQL query that returns entities involving a many to many relationship
I need a JPQL query that returns: 我需要一个返回的JPQL查询:
I tried something like: 我尝试过类似的东西:
SELECT t
FROM Tweet t
WHERE t.author.id = :userId
OR t.author.id IN (
SELECT u.followedUsers
FROM User u
WHERE u.id = :userId
)
Only to find out that the subquery has wrong syntax . 只是发现子查询语法错误 。 Also I cannot call the relation table User_User, like I would in SQL, because JPA doens't recognize it 此外,我不能像在SQL中那样调用关系表User_User,因为JPA不会识别它
User 用户
@Entity
public class User {
@Id
@GeneratedValue
private long id
@ManyToMany(mappedBy = "followedUsers")
private Set<User> followers;
@ManyToMany
private Set<User> followedUsers;
}
Tweet 鸣叫
@Entity
public class Tweet {
@Id
@GeneratedValue
private long id;
@ManyToOne
private User author;
}
given this query 鉴于此查询
OR t.author.id IN (
SELECT u.followedUsers
FROM User u
WHERE u.id = :userId
)
you are trying to find an Integer (t.author.id)
in a list of User
objects ! 您正试图在User
对象列表中找到Integer (t.author.id)
! I think this should work : 我认为这应该有效:
SELECT t
FROM Tweet t
WHERE t.author.id = :userId
OR t.author MEMBER OF (
SELECT u.followedUsers
FROM User u
WHERE u.id = :userId
)
Edit 编辑
... MEMBER OF (subquery)...
isn't allowed, but merging the subquery into its parent resolves this. ... MEMBER OF (subquery)...
是不允许的,但将子查询合并到其父级中会解决此问题。
SELECT DISTINCT(t)
FROM Tweet t, User u
WHERE t.author.id = :userId
OR (t.author MEMBER OF u.followedUsers AND u.id = :userId)
I have the habit of making JPQL queries more similar to SQL queries. 我习惯让JPQL查询更类似于SQL查询。 So, my suggestion: 所以,我的建议是:
SELECT t FROM Tweet t
JOIN t.author a
WHERE a.id = :idUser
OR a.id IN (SELECT followedUser.id
FROM User u
JOIN u.followedUsers followedUser
WHERE u.id = :idUser)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.