Search code examples
javajpamany-to-manyjpqlnamed-query

JPQL query that returns entities involving a many to many relationship


I need a JPQL query that returns:

  • All Tweets that I posted
  • All Tweets that are posted by users whom I follow (this is the many to many part)

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

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;

}

Solution

  • I have the habit of making JPQL queries more similar to SQL queries. 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)