【问题标题】:HQL. How to create a query that returns all the Lines with a List<Point> between dates高质量的。如何创建一个查询,该查询返回日期之间具有 List<Point> 的所有行
【发布时间】: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 &lt; :ed AND p.x &gt; :sd的东西吗?
  • 好像和我的例子一样。问题是线条不应包含这些日期中未包含的点,但作为此查询的结果,如果此间隔中包含的线条中至少有一个点,我将获得包含所有点的线条。但是如果这条线没有这样的点,那么我就不会得到这样的一条线。我需要总是得到所有的线条,但它们每个的点都在日期之间。即使这条线没有这样的点,我也想得到这条线,但是有一个空的点列表。

标签: hibernate jpa select hql jpql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 2014-11-03
    相关资源
    最近更新 更多