[英]Spring Data JPA: How to get distinct record on LEFT JOIN field in JPA Specification
[英]Left Join in Spring Data JPA's Specification
假設我有以下課程:(簡化到極致)
@Entity
@Table(name = "USER")
public class User {
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private BillingAddress billingAddress;
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
private ShippingAddress shippingAddress; // This one CAN be null
}
並且兩個*Address
都繼承自這個摘要:(再次,它是額外簡化的)
public abstract class Address {
@OneToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
@NotEmpty
@Size(max = 32)
@Column(name = "ADDR_TOWN")
private String town;
}
我嘗試了 JPA 規范,如 Spring 的博客文章所述:
/**
* User specifications.
*
* @see <a href="https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl">Advanced Spring Data JPA - Specifications and Querydsl</a>
*/
public class UserSpecifications {
public static Specification<User> likeTown(String town) {
return new Specification<User>() {
@Override
public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
return cb.like(cb.lower(root.get("billingAddress").get("town")), '%' + StringUtils.lowerCase(town) + '%');
}
};
}
使用這個“規范”如下:
List<User> users = userRepository.findAll(UserSpecifications.likeTown(myTown));
但是現在,我還想在城鎮中搜索可能不存在的shippingAddress。 我嘗試將cb.like
與cb.or
結合使用,但結果是結果 SQL 查詢對 shippingAddress 有一個 INNER JOIN,這是不正確的,因為如上所述,它可能為空,所以我想要一個 LEFT JOIN .
怎么做?
謝謝。
指定連接類型:
town = '%' + StringUtils.lowerCase(town) + '%';
return cb.or(
cb.like(cb.lower(root.join("billingAddress", JoinType.LEFT).get("town")), town),
cb.like(cb.lower(root.join("shippingAddress", JoinType.LEFT).get("town")), town));
不知道有沒有幫助。
我有同樣的問題。 我可以解決它的唯一方法是使用子查詢。
例如,這將類似於以下內容:
JPASubQuery subquery = new JPASubQuery();
subquery = subquery .from( /* tableB */);
subquery .where(/* conditions */);
然后使用我將子查詢添加到謂詞:
predicate.and(subquery.exists());
注意:就我而言,它有幫助,因為我廣泛使用規范。 在大多數情況下,性能影響似乎並不大。
編輯:我剛剛意識到前一個例子只適用於我的情況,因為我使用的是query-dsl
。
在您的情況下,請查看JPA 2.0、Criteria API、Subqueries、In Expressions以創建子查詢並將其加入您的謂詞條件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.