输入包含最后一个值的列表

时间:2016-02-23 18:18:39

标签: 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,或者我需要在每条记录上循环以获取此信息?

@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;
}

1 个答案:

答案 0 :(得分:2)

有几个选择:

一个(非JPA,仅限Hibernate)

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

https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/performance.html

  

&#34;特懒惰&#34;集合提取:个人元素   根据需要从数据库访问集合。 Hibernate尝试   除非绝对,否则不要将整个集合提取到内存中   需要。它适用于大型系列。

映射将如下所示:

@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); 
}

两个(非JPA,仅限Hibernate。)

使用@Where注释过滤集合,以便在@OneToMany时,只能访问一个元素。

https://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-hibspec-collection

映射将如下所示:

@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 {

}