hi I am trying to make a JPA custom query call using Examplematcher . Below is the code i am trying . If i get the stateId i need to use it in query condition otherwise i need pull all counties irrespective of state . I dont want to make two repo calls like to achieve it in a single repo call .
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;
}
If i make the repo call with just string stateId like below its working , but if stateId is empty it will bring back empty result , i need all need to comeback .
countiesRepository.findAllByStateCountyIdStateIdOrderByStateCountyIdCountyNameAsc
(stateId)
.stream().map(this::countyAsDropDown).collect(Collectors.toList());
CodePudding user response:
Use a Specification
like this:
@Repository
public interface CountiesRepository extends JpaRepository<StateCounty, StateCountyId> {
List<StateCounty> findAllByStateCountyIdStateIdOrderByStateCountyIdCountyNameAsc(Specification<StateCounty> specification);
}
countiesRepository.findAllByStateCountyIdStateIdOrderByStateCountyIdCountyNameAsc(
(root, query, cb) -> {
if (stateId == null) return null;
return cb.equal(root.get("stateCountyId").get("stateId"), stateId);
}
)
.stream().map(this::countyAsDropDown).collect(Collectors.toList());