1

花了大约 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
4

1 回答 1

1

查询正确,但关系定义存在问题。这是我所拥有的:

@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;
    ...
}

看来我必须像这样指定User和之间的关系Post

    @OneToMany(mappedBy = "author")
    private List<Post> posts;
于 2013-02-07T05:35:13.847 回答