如何在JPA自定义findAll查询中应用示例匹配器

y0u0uwnf  于 2022-11-14  发布在  其他
关注(0)|答案(1)|浏览(142)

你好,我正在尝试使用Examplematcher进行JPA自定义查询调用。下面是我正在尝试的代码。如果我得到stateId,我需要在查询条件中使用它,否则我需要拉所有县,而不考虑州。我不想像在一个repo调用中实现它那样进行两个repo调用。

StateCountyId stateCountyId = new StateCountyId();
StateCounty stateCounty = new StateCounty();
if(null != stateId){
  stateCountyId.setStateId(stateId);
}
stateCounty.setStateCountyId(stateCountyId);
return countiesRepository.findAllByStateCountyIdStateIdOrderByStateCountyIdCountyNameAsc
 (Example.of(stateCounty,  ExampleMatcher.matchingAll().withIgnoreCase()))
 .stream().map(this::countyAsDropDown).collect(Collectors.toList());

@Repository
public interface CountiesRepository extends JpaRepository<StateCounty, StateCountyId> {
List<StateCounty> findAllByStateCountyIdStateIdOrderByStateCountyIdCountyNameAsc(Example 
stateId);
}

@Entity
@Builder
public class StateCounty implements Serializable {
@EmbeddedId
StateCountyId stateCountyId;
@Column(name = "CODE_NBR")
private String codeNbr;
}

@Embeddable
@EqualsAndHashCode
public class StateCountyId implements Serializable {
@Column(name = "STATE_ID")
private String stateId;
@Column(name = "COUNTY_NAME")
private String countyName;
}

如果我用字符串stateId调用repo,就像下面的工作一样,但是如果stateId是空的,它将返回空的结果,我需要所有需要恢复。

countiesRepository.findAllByStateCountyIdStateIdOrderByStateCountyIdCountyNameAsc
(stateId)
.stream().map(this::countyAsDropDown).collect(Collectors.toList());

相关问题