具有Join和继承的JPA Criteria API查询

时间:2014-05-08 23:25:45

标签: spring jpa jpa-2.0 criteria-api

我正在尝试使用JPA Criteria API编写Query。我有以下课程:

Class Booking {

  @ForeignKey(name = "BVisit_ID_FK")
  private List<BVisit> BVisits = new LinkedList<>();

    //other properties
    ...
}

Class Visit{

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "ID")
  private Long id;

}

Class VisitSpecial extends Visit{

  @Column(name = "ARRIVAL_TIME", nullable = false)
  private Date arrivalTime;

  @Column(name = "DEPARTURE_TIME", nullable = false)
  private Date departureTime;

  //other properties...
}`

如何使用JPA Criteria Api(和元模型)编写查询,找到所有预订 访问日期值(参数),介于最短到达时间,预订访问的最长出发时间。 我使用org.springframework.data.jpa.domain.Specification

查询应如下所示:

SELECT Booking 
from Booking B, Visit V, VisitSpecial VS
where Visit.bookingId = Booking.id and Visit.id = VisitSpecial.id
      and VisitSpecial.arrivalTime = (SELECT MIN(VisitSpecial.arrivalTime) from VisitSpecial VS1 WHERE V.id = VS1.id)
      and VisitSpecial.arrivalTime <= :date
      and VisitSpecial.departureTime = (SELECT MAX(VisitSpecial.departureTime) from VisitSpecial VS1 Where V.id = VS1.id)
      and VisitSpecial.departureTime >= :date

1 个答案:

答案 0 :(得分:2)

有关通过JPA标准InheritanceType.JOINED处理Subquery和其他继承策略的信息,请参见我的答案here

使用treat进行向下转换可能有效,但我不建议将其用于复杂查询,因为它可能会产生效率低下的查询(冗余连接),或者完全无法基于您的JPA提供程序(Hibernate,Eclipselink等)运行。