我正在使用 java 8 在 spring-boot 上制作一個 crud,我想知道如何通過外鍵進行過濾。就像尋找生活在確定城市中的人一樣。例如:localhost:8080/people?cityName=LasVegas
我正在使用 JPA 查詢來獲取資料庫中的資料
(Pessoa) 是我的物體類
我的倉庫:
@Repository
public interface CidadeRepository extends JpaRepository<Cidade, Long> {
@Query("select c from Cidade c where c.nome is null or c.nome like %:filtro% and c.estado is null or c.estado = :filtro")
Page<Cidade> listarPorFiltros(@Param("filtro") CidadeDTO filtro, Pageable pageable);
}
佩索阿資源:
@GetMapping
public ResponseEntity<Page<PessoaDTO>> listarPessoas(
@ModelAttribute PessoaDTO pessoaDTO, Pageable pageable){
return new ResponseEntity<>(pessoaService.listarPessoas(pessoaDTO, pageable), HttpStatus.OK);
}
佩索阿DTO:
@Getter
@Setter
public class PessoaDTO implements Serializable {
private Long id;
private String nome;
private String cpf;
private String apelido;
private String timeCoracao;
private String hobbie;
private CidadeDTO cidadeDTO;
}
cidadeDTO 是我試圖過濾的 fk ^^
佩索阿服務:
/*Pesquisar pessoas por nome, cpf ou cidade*/
public Page<PessoaDTO> listarPessoas(PessoaDTO pessoaDTO, Pageable pageable){
Page<PessoaDTO> pessoaPage;
if(pessoaDTO.getNome() != null){
pessoaPage = pessoaRepository.listarPorFiltros(pessoaDTO.getNome(), null, null, pageable).map(pessoaMapper::pessoaParaDTO);;
}else if(pessoaDTO.getCpf() != null){
pessoaPage = pessoaRepository.listarPorFiltros(null, pessoaDTO.getCpf(), null, pageable).map(pessoaMapper::pessoaParaDTO);;
}else if(pessoaDTO.getCidadeDTO().getNome() != null){
pessoaPage = pessoaRepository.listarPorFiltros(null, null, pessoaDTO.getCidadeDTO().getNome(), pageable).map(pessoaMapper::pessoaParaDTO);;
}else{
pessoaPage = pessoaRepository.findAll(pageable).map(pessoaMapper::pessoaParaDTO);
}return pessoaPage;
}
佩索阿映射器:
@Component
@Mapper(componentModel = "spring")
public interface PessoaMapper {
@Mapping(source = "cidade", target = "cidadeDTO")
PessoaDTO pessoaParaDTO(Pessoa pessoa);
List<PessoaDTO> pessoaParaDTO(List<Pessoa> pessoa);
Pessoa pessoaDTOParaPessoa(PessoaDTO pessoaDTO);
}
uj5u.com熱心網友回復:
我無法過濾 cityName,因為在我的“PessoaDTO”中沒有代表 cityName 的變數,只有城市(物體)。
因此,我創建了一個名為“SearchPessoaDTO”的新類,其中包含一個用于存盤 cityName 的字串變數。我還更改了查詢以正常作業。
我的倉庫:
@Query("select c from Cidade c where c.nome is not null and c.nome like %:nome% or c.estado is not null and c.estado = :estado")
Page<Cidade> listarPorFiltros(@Param("nome") String nome, @Param("estado") String estado, Pageable pageable);
搜索佩索阿DTO:
@Getter
@Setter
public class PessoaDTO implements Serializable {
private String nome;
private String cpf;
private String c_nome;
}
現在,如果我想搜索住在 york 的人,我會發出這樣的 GET 請求:localhost:8080/api/pessoas?c_nome=York
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432646.html
