每组JPA最新一行

时间:2017-11-27 16:36:04

标签: java jpa orm

我有一个具有以下结构的表:

审核表

|    ID     |   User    |  Log In Date  |    Other Info e.g. IP    |
|-----------|-----------|---------------|--------------------------|
|     0     |     1     |   2017/11/10  |           ...            |
|     1     |     1     |   2017/12/10  |           ...            |
|     2     |     2     |   2017/10/10  |           ...            |
|     3     |     3     |   2017/09/08  |           ...            |

在我的AuditRepository中,我想创建一个方法,为每个用户提取最新/最新登录日期的Audit

审核

@Entity
@Table(name = "Audit")
public class Audit {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    private Instant loginDate

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "User")
    private User user;

    // Other fields
}

如何编写可以实现此目的的存储库@Query

到目前为止,我已经尝试了

@Query(value =
           "SELECT a FROM Audit a " +
           "LEFT JOIN Audit a1 ON a.loginDate > a1.loginDate AND a.user = a1.user " +
           "WHERE a1.user IS NULL"
    )

但我得到了例外QuerySyntaxException: Path expected for join!

1 个答案:

答案 0 :(得分:2)

您可以尝试相关的子查询:

SELECT a FROM Audit a 
  inner join a.user u
where a.loginDate = (
        select max(a1.loginDate) 
        from audit a1 inner join a1.user u1 
        where u1.id = u.id and a1.id = a.id
)