简体   繁体   English

JPA命名查询联接

[英]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 我遇到了JPA问题,我需要返回用户列表,但我总是得到ID所属的用户

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) 此查询始终返回id参数的用户(param = 1返回user1而不是您跟随的所有用户)

  @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. 该表看起来像这样,两列都是用户表的ID。

As you can see: 如你看到的:

  • user4 got 2 followers user4有2位关注者
  • user3 got 1 follower user3有1个关注者
  • user 2 is following 2 users 用户2正在关注2个用户
  • user 1 is following 1 user 用户1正在关注1个用户

桌子

This is the user table 这是用户表

用户表

The follower table is generated by JPA with a arraylist 跟随者表是由JPA使用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) 作为用户2,我可以看到我正在跟踪用户3和用户4。但是,如果我是用户3,则看不到用户2正在跟踪我(这总是以某种方式返回用户3)

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? 为什么不执行“从用户u where u.id =:id中选择u”并通过java代码中的u.getFollowers()访问关注者? You don't explicitly need the join if your entities have the relationship. 如果您的实体具有关系,则不需要显式需要联接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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