Jpa 为列表提供最后一个值

Jpa 为列表提供最后一个值,jpa,Jpa,我有这些实体,我做这个查询 select r from RentAmount r Join r.lodger l join l.bailList b where r.unpaidBalance > 0 and (r.paymentDueDate > :date or r.paymentDueDate is null ) and b.paymentPeriod= order by r.rentAmountId") 有没有办法只给Lodger.bailList提供最后一次保释,或者我

我有这些实体,我做这个查询

select r from RentAmount r Join r.lodger l join l.bailList b where r.unpaidBalance > 0 and (r.paymentDueDate > :date  or r.paymentDueDate is null ) and b.paymentPeriod= order by r.rentAmountId")
有没有办法只给Lodger.bailList提供最后一次保释,或者我需要循环每个记录来获取此信息

@Entity
public class RentAmount {

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

  @OneToOne
  private Lodger lodger;

}

@Entity
public class Lodger{

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

  @OneToOne(fetch = FetchType.LAZY, mappedBy="lodger")
  private RentAmount rentAmount;

  @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY, mappedBy = "lodger", orphanRemoval = true)
  private List<Bail> bailList;

}

@Entity
public class Bail {

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

  @Enumerated(EnumType.STRING)
  private PaymentPeriodEnum paymentPeriod;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "lodger_id")
  private Lodger lodger;
}
@实体
公屋租金{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
私人长租公寓;
@奥内托内
私人房客;
}
@实体
公屋住客{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
私人长房客;
@OneToOne(fetch=FetchType.LAZY,mappedBy=“lodger”)
私人租金金额租金金额;
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE},fetch=FetchType.LAZY,mappedBy=“lodger”,orphanRemoving=true)
私人名单;
}
@实体
公开保释{
@身份证
@GeneratedValue(策略=GenerationType.AUTO)
私人长贝利德;
@枚举(EnumType.STRING)
私人付款期Enum付款期;
@manytone(fetch=FetchType.LAZY)
@JoinColumn(name=“房客id”)
私人房客;
}

有几个选项:

One(非JPA,仅休眠)

确保集合的顺序正确,并将其标记为额外延迟。您可以访问整个集合,但访问单个项目不会触发满载

“额外惰性”集合获取:集合的单个元素 根据需要从数据库访问集合。冬眠 不将整个集合提取到内存中,除非绝对 需要。它适用于大型收藏

映射将如下所示:

@OneToMany(mappedBy = "lodger")
@LazyCollection(LazyCollectionOption.EXTRA)
@OrderBy("theRelevantProperty ASC")
private List<Bail> bailList;

public void getCurrentBail(){
    //will only load this item from the database
    return bailList.get(bailList.size() - 1); 
}
@OneToMany(mappedBy = "lodger")
@Where(clause="some native sql which will filter to include onyl 1item"))
private List<Bail> bailList;

public void getCurrentBail(){
    //will be the only item accessible
    return bailList.get(0);
}
三个(符合JPA)

将涉及在数据库级别创建视图。这方面的各种选择。如果我们只对当前的保释感兴趣,那么这种观点将类似于上面的选项2。只需将Bail实体指向此视图,而不是具体表格:

@Entity
@Table(name = "vw_active_bail")
public class Bail {

}

您使用的是什么JPA实现?Hibernate提供了几种可能性。另一个(符合JPA的)解决方案是数据库视图。