![](/img/trans.png)
[英]Spring Data JPA Specification search for property in nested collection
[英]spring data jpa find all by example nested collection property
我有兩個對象。 可以有多個嵌套地址的公司。
@Entity
@Data
@Table(name = "company")
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "phone")
private String phone;
@OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
private List<Address> addresses;
}
地址類如下所示:
@Data
@Entity
@Table(name = "address")
@ToString(exclude = "company")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "postal_code")
private String postalCode;
@Column(name = "city")
private String city;
@Column(name = "street")
private String street;
@JsonIgnore
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "company_id")
private Company company;
}
如果可能的話,我想以某種方式進行動態查詢,搜索嵌套的集合屬性。 我做了一個使用示例匹配器的搜索方法,但結果是錯誤的。 每次我從 DB 獲得所有信息時,不僅僅是我正在尋找的具有地址郵政編碼的公司。
我的搜索方法如下所示:
@PostMapping("/search")
public List<Company> search(@RequestBody final Company company){
return companyRepository.findAll(Example.of(company,
ExampleMatcher.matchingAny()
.withIgnoreNullValues()
.withIgnorePaths("id")
.withStringMatcher(ExampleMatcher.StringMatcher.STARTING)));
}
如您所見,我從 DB 收到了所有內容,而不是唯一一家地址郵政編碼以 1 開頭的公司。
嗨,您可以使用Specification<T>
https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
為此,您需要從接口 JpaSpecificationExecutor 擴展:
public interface UserRepository extends JpaRepository<User> ,JpaSpecificationExecutor<User>{
}
而且您還需要實現您的自定義Specification<T>
然后你可以使用 repository.findAll(your impleneted Specification);
春季文檔:
我認為這很有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.