返回涉及多对多关系的实体的JPQL查询

时间:2017-04-08 12:16:50

标签: java jpa many-to-many jpql named-query

我需要一个返回的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中那样调用关系表User_User,因为JPA不会识别它

用户

@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;

}

2 个答案:

答案 0 :(得分:1)

给出此查询

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

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

 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)

答案 1 :(得分:0)

我习惯让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)