JPQL 查询 returns 个涉及多对多关系的实体

JPQL query that returns entities involving a many to many relationship

我需要一个 returns:

的 JPQL 查询

我试过类似的方法:

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
)

才发现子查询有wrong syntax。我也不能像在 SQL 中那样调用关系 table User_User,因为 JPA 无法识别它

用户

@Entity
public class User {

    @Id
    @GeneratedValue
    private long id

    @ManyToMany(mappedBy = "followedUsers")
    private Set<User> followers;

    @ManyToMany
    private Set<User> followedUsers;

}

推文

@Entity
public class Tweet {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne
    private User author;

}

给出这个查询

OR t.author.id IN (
            SELECT u.followedUsers
            FROM User u
            WHERE u.id = :userId
        )

您正试图在 User 个对象的列表中找到整数 (t.author.id)! 我认为这应该有效:

 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
    )

编辑

... 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)

我习惯使 JPQL 查询更类似于 SQL 查询。所以,我的建议:

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)