首页 > 解决方案 > 高质量的。如何创建一个返回所有行的查询日期之间

问题描述

我有两个实体:线和点

@Entity
@Table(name = "line")
public class Line {
    private long id;
    private String name;

    @OneToMany
    @JoinColumn(name = "line_id")
    private List<Point> points;
}

@Entity
@Table(name = "point")
public class Point {
    @Id
    private long id;

    @Column(name = "x")
    private LocalDateTime x;

    @Column(name = "y")
    private int y;
}

select * from line;
+----+----------------------+
| id | name                 | 
+----+----------------------+
|  1 | lineA                |         
|  2 | lineB                |  
+----+----------------------+  

select * from point;
+----+--------------------------------------+----------+
| id |              x             |     y   |  line_id |
+----+-------------------------------------------------+
|  1 | 2016-01-01 02:00:00.000000 |     1   |      1   |
|  2 | 2017-01-01 02:00:00.000000 |     2   |      1   |
|  3 | 2018-01-11 02:00:00.000000 |     1   |      1   |
|  4 | 2019-01-01 02:00:00.000000 |     3   |      1   |
|  5 | 2015-01-01 02:00:00.000000 |     2   |      2   |
|  6 | 2016-01-01 02:00:00.000000 |     1   |      2   |
|  7 | 2017-01-01 02:00:00.000000 |     3   |      2   |
|  8 | 2018-01-01 02:00:00.000000 |     2   |      2   |
+----+----------------------------+---------+----------+

HQL 查询应该是什么样子,以便它返回包含两个日期之间的点的所有行 (List) 的列表?

entityManager.createQuery("select distinct l from Line l join l.points p where p.x between :sd and :ed)").setParameter("sd", LocalDateTime.of(2017, 1, 1, 0, 0)).setParameter("ed", LocalDateTime.of(2018, 1, 1, 0, 0)).getResultList()

这样的请求将返回日期间隔中至少有一个点的行。在这种情况下,这条线将包含它拥有的所有点。但我需要返回仅包含这两个日期之间的点的所有行。

我怀疑这很简单。但由于我是 hql 和 sql 的新手,我不知道该怎么做。

标签: hibernatejpaselecthqljpql

解决方案


目前通过拆分为单独的请求来解决。首先,所有线都得到,然后,对于每条线,点得到


推荐阅读