在一个jpql查询中获取每种类型的一些记录

时间:2017-07-24 15:38:45

标签: spring jpa spring-data spring-data-jpa jpql

我有两个实体 - 人物和记录:

@Entity
public class Person {
    @Id
    @GeneratedValue
    private Long id;

    @JsonIgnore
    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Record> records;
}


@Entity
public class Record {
@Id
    @GeneratedValue
    private Long id;

@ManyToOne
    @JoinColumn(name = "person", referencedColumnName = "id", nullable = false)
    private Person person; 
}

我需要在一个查询中为每个现有人获得5条记录。

我为jpql找到的唯一解决方案如下:

"SELECT r FROM Person p LEFT JOIN p.records r WHERE r.id IN " +
            "(SELECT r1.id FROM Record r1 WHERE r1.person = p AND " +
            "(SELECT Count(r2) FROM Record r2 WHERE r2.person = r1.person AND r2.id < r1.id) <= 5)

但可能在春季jpa中有一个更优雅的解决方案。

有没有人有任何想法?

1 个答案:

答案 0 :(得分:0)

您可以在 ToMany 一侧使用javax.validation.constraints.Size注释,限制最大括号

//..ToMany and other annotations
@javax.validation.constraints.Size(min=0, max=5)
private List<Record> records;