【问题标题】:Fetch 100 rows from child entity for each element from IN clause从子实体中为 IN 子句中的每个元素获取 100 行
【发布时间】:2020-11-18 05:28:16
【问题描述】:

父子关系:OneToMany

Parent - table
+-----+---------+
|id   |   name  |
+-----+---------+
| 1   |  name1  |
| 2   |  name2  |
| 3   |  name3  |
+---------------+

child1 - table 
+--+---------+------+
|id|parent_id|name  |
+--+---------+------+
| 1|   1     |  qwe |
| 2|   1     |  asd | 
| 3|   1     |  dsf |
| 4|   2     |  xzc |
+--+---------+------+

表:公司(父)和雇员(子)。我想获取所有给定公司的 100 名最近加入的员工以及公司的详细信息。

SELECT c.*, e.* 
FROM company c 
JOIN (
    SELECT * 
    FROM employee 
    WHERE company_id IN(2,3,4,5) 
    ORDER BY joined_at DESC LIMIT 100
) e on e.company_id = c.id where c.id in (2,3,4,5)

上面的查询一共只返回了 100 名员工,但我希望 IN 子句中提供的每个公司都有 100 名员工。

【问题讨论】:

标签: mysql hibernate jdbc one-to-many hibernate-mapping


【解决方案1】:

您可以使用 Pageable 来获取知道父实体的子实体。 请注意,此查询将返回 Child 的分页结果。

 /**
  * Find Child entities knowing the Parent.
  */
  @Query("select child from Parent p inner join p.childs child where p = :parent")
  public Page<Child> findBy(@Param("parent") Parent parent, Pageable pageable);

你可以这样使用它:

Page<Child> findBy = repo.findBy(parent, new PageRequest(page, size));

【讨论】:

  • 我想要父母的详细信息以及孩子的详细信息。
猜你喜欢
  • 1970-01-01
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
  • 2018-11-01
  • 2020-01-09
  • 1970-01-01
  • 2021-02-10
相关资源
最近更新 更多