簡體   English   中英

JPQL-左聯接一對多

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

花了大約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

查詢是正確的,但是關系定義存在問題。 這是我所擁有的:

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

看來我必須像這樣指定UserPost之間的關系:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM