简体   繁体   English

JPQL-左联接一对多

[英]JPQL - left join with count for many in one-to-many

Spent about 2 hours trying to understand why JPQL query doesn't return me what I expect. 花了大约2个小时尝试了解JPQL查询为什么没有返回我期望的结果。 Please consider the code: 请考虑以下代码:

    System.out.println("JPQL ----------------------------");
    Query q = em.createQuery(
            "select u.userName, count(p.id) from User u " + 
            "left join u.posts p group by u.userName");
    List x = q.getResultList();     
    for(Object o : x) {
        Object[] y = (Object[])o;
        System.out.printf("%s %s\n", y[0], y[1]);
    }

    System.out.println("Spring Data JPA -----------------");
    for(User user : userRepository.findAll()) {
        List<Post> posts = postRepository.findAllByAuthor(user);
        System.out.printf("%s %s\n", user.getUserName(), posts.size());
    }

Output is: 输出为:

JPQL ----------------------------
user1 0
user2 0
Spring Data JPA -----------------
user1 3
user2 10

I expect JPQL approach to print the same as what repository approach does. 我希望JPQL方法可以打印出与存储库方法相同的方法。 Where's the mistake? 哪里错了?

Update 更新

Here's what SQL trace says: 这是SQL跟踪显示的内容:

select 
  user0_.userName as col_0_0_, 
  count(post2_.id) as col_1_0_ 
from User user0_ 
left outer join User_Post posts1_ 
  on user0_.id=posts1_.User_id 
left outer join Post post2_ 
  on posts1_.posts_id=post2_.id 
group 
  by user0_.userName

Query was correct, but there was issue with relationships definition. 查询是正确的,但是关系定义存在问题。 Here's what I had: 这是我所拥有的:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    ...         
    @OneToMany
    private List<Post> posts;
    ...
}

@Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    ...
    @ManyToOne
    private User author;
    ...
}

It appeared that I have to specify relationship between User and Post like this: 看来我必须像这样指定UserPost之间的关系:

    @OneToMany(mappedBy = "author")
    private List<Post> posts;

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

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