Home > Mobile >  Error locating String field in Spring Boot
Error locating String field in Spring Boot

Time:04-01

I'm trying to find a company by its CNPJ(Brazilian corporate tax payer registry number) in a DB (H2), but it's returning an error

{
 "timestamp": "2022-03-30T19:30:23.823 00:00",
 "status": 404,
 "error": "Not Found",
 "path": "/companies/cnpj/30101554000146"
}

I've tried other alternatives using:

http://localhost:8080/companies/cnpj/'30.101.554/0001-46', http://localhost:8080/companies/cnpj/"30.101.554/0001-46",

but the error persists. I implemented like this :

@Entity
@Table(name = "company")
 public class Company implements Serializable {

 private static final long serialVersionUID = 1L;

 @Id
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private Long id;

 private String name;
 @CNPJ
 private String cnpj;

//skipped
}

public interface CompanyRepository extends JpaRepository<Company,Long> {

 Optional<Company> findByCnpj(String cnpj);
}

public class CompanyDTO {
 private Long id;

 private String name;

 private String cnpj;

//skipped
}

@Service
@Transactionalpublic class CompanyService {

 @Autowired
 private CompanyRepository companyRepository;

 @Transactional(readOnly = true)
 public CompanyDTO findById(Long id) {
    Company resultado = companyRepository.findById(id).get();
    CompanyDTO dto = new CompanyDTO(resultado);
    return dto;
 }  

 @Transactional(readOnly = true)
 public CompanyDTO findByCnpj(String cnpf) {
    Optional<Company> resultado = companyRepository.findByCnpj(cnpf);
    CompanyDTO dto = new CompanyDTO(resultado.get());
    return dto;
    
 }
}

@RestController
@RequestMapping(value = "/companies")public class CompanyController {

 @Autowired
 private CompanyService companyService;


 @GetMapping(value = "/{id}")
 public CompanyDTO findById(@PathVariable Long id) {
    return companyService.findById(id);
 }

 @GetMapping(value = "/cnpj/{cnpj}")
 public CompanyDTO findByCnpj(@PathVariable String cnpj) {
    return companyService.findByCnpj(cnpj);
 }
}

The expected output would be:

[
  {"id": 1,
   "nome": "Company 123",
   "cnpj": "30.101.554/0001-46"
  }
]

UPDATE:

I changed @GetMapping(value = "/cnpj/{cnpj}") to @GetMapping(value = "/cnpj/**") and:

@GetMapping(value = "/cnpj/**")
     public CompanyDTO findByCnpj(HttpServletRequest request) {
        return companyService.findByCnpj(request.getRequestURI().split(request.getContextPath()   "/cnpj/")[1]);
     }

Works for me! Thanks

CodePudding user response:

As explained here, pathParams with slashes can be realy tricky while using spring-boot. This article explains pretty well what to do to avoid getting an error 404 when your pathVariable has a slash.

  • Related