【发布时间】:2019-07-01 11:56:24
【问题描述】:
我有两个实体:线和点
@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 的新手,所以我不知道该怎么做。
【问题讨论】:
-
你试过类似
p.x < :ed AND p.x > :sd的东西吗? -
好像和我的例子一样。问题是线条不应包含这些日期中未包含的点,但作为此查询的结果,如果此间隔中包含的线条中至少有一个点,我将获得包含所有点的线条。但是如果这条线没有这样的点,那么我就不会得到这样的一条线。我需要总是得到所有的线条,但它们每个的点都在日期之间。即使这条线没有这样的点,我也想得到这条线,但是有一个空的点列表。
标签: hibernate jpa select hql jpql