首页 > 解决方案 > 从子实体中为 IN 子句中的每个元素获取 100 行

问题描述

父子关系: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 名员工。

标签: mysqlhibernatejdbcone-to-manyhibernate-mapping

解决方案


您可以使用 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));

推荐阅读