简体   繁体   中英

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

桌子

This is the 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM