带有DISTINCT ON的JpaRepository方法名称

时间:2016-12-20 09:05:11

标签: spring-data-jpa

我正在创建Spring应用程序,我正在使用JpaRepository来简化数据库查询。

我在使用DISTINCT ON的JpaRepository约定创建方法名称时遇到问题。这是我的SQL查询:

SELECT DISTINCT ON (s.device_id)
  s.status_id,
  s.error,
  s.receive_time,
  s.device_id
FROM statuses s
ORDER BY s.device_id, s.receive_time DESC

我尝试过这样的名字,但它不起作用:

List<Status> findDistinctByDeviceId_OrderByReceiveTimeDesc();

这是我的课程(简化):

public class Status {
    private long status_id;
    private String error;
    private Date receive_time;
    private Device device_id;
}

public class Device {
    private long device_id;
    private String name;
}

甚至可以在方法名称中使用DISTINCT ON吗?我不想使用SQL查询,因为我的类比上面复杂得多,我想添加每个字段来查询。

2 个答案:

答案 0 :(得分:2)

据我所知, DISTINCT ON 是特定于数据库的,而不是全局SQL命令。它看起来就像一列一样明显。

但是如果你想要对整个SQL行进行DISTINCT,你可以这样做:

// Spring Data allows you to specify the entity you want to distinct after the word "Distinct"
List<Status> findDistinctStatusByOrderByReceiveTimeDesc();

// Or before the word "Distinct"
List<Status> findStatusDistinctByOrderByReceiveTimeDesc();

这已经确保您不会收到任何重复的行,创建一个SQL输出,如:

SELECT DISTINCT 
  s.device_id,
  s.status_id,
  s.error,
  s.receive_time,
  s.device_id
FROM statuses s
ORDER BY s.device_id, s.receive_time DESC

有关此内容的更多信息,您可以查看Spring Data Documentation

答案 1 :(得分:1)

我使用过这样的东西,但是有效:

@Query(value = "select distinct on (s.device_id) s.* " +
        "from statuses s " +
        "order by s.device_id, s.receive_time desc",
        nativeQuery = true)
public List<Status> getStatuses();
相关问题