简体   繁体   中英

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. 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. Where's the mistake?

Update

Here's what SQL trace says:

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:

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

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