花了大约 2 个小时试图理解为什么 JPQL 查询没有返回我期望的结果。请考虑代码:
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());
}
输出是:
JPQL ----------------------------
user1 0
user2 0
Spring Data JPA -----------------
user1 3
user2 10
我希望 JPQL 方法与存储库方法的打印方式相同。哪里错了?
更新
这是 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