我有以下实体,想知道如何使用JPA规范创建以下查询。
SELECT p.*
FROM property p
INNER JOIN ad
ON ad.id = p.ad_id
LEFT JOIN featured_ad fad
ON fad.id = ad.id
ORDER BY fad.start_date DESC,
ad.created_ts DESC
实体(删除了方法和其他属性以简化类):
public class Ad {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
private User user;
}
public class Property implements {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToOne
@JoinColumn(unique = true)
private Ad ad;
@OneToOne
@JoinColumn(unique = true)
private Location location;
}
public class FeaturedAd {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "status", nullable = false)
private FeaturedAdStatus status;
@Column(name = "start_date")
private Instant startDate;
@Column(name = "end_date")
private Instant endDate;
@ManyToOne
private Ad ad;
}
我可以加入带有属性的属性而不会出现问题,但可以加入FeaturedAd,然后按start_date排序是我不知道的。
specification = specification.and(new Specification<Property>() {
@Override
public Predicate toPredicate(Root<Property> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
final Join<Ad, Property> adProperty = root.join("ad", JoinType.INNER);
//how to join to featuredAd the order by startDate?
// what to return here?
}
});