我有两个对象。可以有多个嵌套地址的公司。
@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 开头的公司。