Search code examples
javajpajoinnamed-query

JPA Named query join


I've got an issue with JPA, I need to return a list of users but I always get the user the id is from

This one is working correctly and returns the users that you are following:

@NamedQuery(name = "User.findByFollowing",
                        query = "select User from User user join user.followers f where f.id=:id"),

This query always returns the user of the id parameter (param=1 returns user1 instead of all the users you are followed by)

  @NamedQuery(name = "User.findFollower",
            query = "select User, f from User user join user.followers f where user.id=:id")

The table looks like this, both columns are id's of the user table.

As you can see:

  • user4 got 2 followers
  • user3 got 1 follower
  • user 2 is following 2 users
  • user 1 is following 1 user

The table

This is the user table

User table

The follower table is generated by JPA with a arraylist

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    private List<User> followers = new ArrayList();

Now you've got some background info I will get to the point.

As user 2 I can see that i am following user3 and user 4. But if I am user 3 I can't see that user2 is following me (This always returns user3 in some way)

If you need more information feel free to ask


Solution

  • Why don't you do "select u from User u where u.id = :id" and access the followers via u.getFollowers() in your java code? You don't explicitly need the join if your entities have the relationship.