限制加入记录的数量

时间:2016-03-15 18:56:19

标签: jpa spring-data-jpa jpa-2.1

我有这个实体

@Entity
public class RentAmount {

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

    private BigDecimal unpaidBalance;

    private BigDecimal cashAdvance;

    private BigDecimal totalRentAmount;

    private LocalDate paymentRentDueDate;

    private LocalDate paymentDueDate;

    @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
    @OrderBy
    private Set<RoomPayment> roomPaymentList;

    @OneToOne
    private Lodger lodger;
}

我的查询

select r from RentAmount r Join fetch r.lodger l join fetch l.bailList b join fetch r.roomPaymentList p where r.paymentRentDueDate <= :date and b.paymentPeriod=:paymentPeriod order by r.rentAmountId

RoomPaymentList可能非常庞大,我搜索的方式是限制返回的记录数。

有没有办法限制来自roomPaymentList的值?

3 个答案:

答案 0 :(得分:2)

如果我理解正确 - 您希望限制每个RoomPaymentList的{​​{1}}行数,但不限制结果集中的行数。如果是这样,JPA就没有这种方式。但是您可以编写一些本机查询或存储过程,并将其限制在子查询等(Example of such query for MS SQL)中。

答案 1 :(得分:0)

如果您有一个普通的MySql查询,可以通过附加

来实现
Limit 5;

到你的查询。 Oracle提供ROWNUM替代方案:

ROWNUM <= 5;

(如此处所述http://www.w3schools.com/sql/sql_top.asp)。

答案 2 :(得分:0)

这可能有助于您使用jpa查询获取10行。

String hql = "select r from RentAmount r Join fetch r.lodger l join fetch l.bailList b join fetch r.roomPaymentList p where r.paymentRentDueDate <= :date and b.paymentPeriod=:paymentPeriod order by r.rentAmountId";
Query query = session.createQuery(hql);
query.setParameter("date", "date");
query.setParameter("paymentPeriod", "paymentPeriod");
List results = query.list();

// If you want to fetch only 10 rows then
query.setMaxResults(10); //it takes only an integer parameter