我正在 Spring Boot 中开发后端,我使用 JPA 进行所有数据库操作。问题如下:
我从前端收到一个名为“responsableServicio”的参数,首先它到达 Controller 方法,在该方法中我检查了参数是否正确到达那里。但是,当参数从 Controller 传递到存储库时,该值未正确获取,它似乎为空,因为我的查询应该返回 1 条记录,而正在返回 0 条记录。
我想强调的是,如果我将参数硬编码到查询中,它会返回正确的结果 1。
我遵循了一些示例,但尚未工作。我究竟做错了什么?提前致谢
公式 Controller
@PostMapping(path = "/getCountAnexos")
@ResponseBody
public String countAnexosRechazo(@RequestBody String responsableServicio) {
Map<String, Object> json = new HashMap<String, Object>();
// Cambiar a nativeQuery
System.out.println("*******************************************");
System.out.println("*******************************************");
System.out.println(responsableServicio);
System.out.println("*******************************************");
System.out.println("*******************************************");
String respuesta = formularioRepository.getAnexosRechazados(responsableServicio);
System.out.printf("RESPUESTA",respuesta);
return respuesta;
}
公式存储库
// Consulta para obtener el numero de Anexos Rechazados de acuerdo el Usuario
@Query(value = "SELECT COUNT(*) FROM formulario where year(fechaTramite)='2020' and responsableServicio = :responsableServicio and (estatusGestorContratos = 'Rechazado' or estatusAFTI = 'Rechazado')", nativeQuery = true)
public abstract String getAnexosRechazados(@Param("responsableServicio") String responsableServicio);
我从控制台得到什么
最佳答案
问题出在 Controller 类中。它将 String 作为带有括号的完整 JSON。 在这里,您采用了 @PostMapping 并使用 @RequestBody String responsableServicio 作为方法参数。您不能将 String 作为类型参数,您必须创建一个类,将 String responsableServicio 作为变量及其 getter/setter。 然后在 Controller 内将参数作为类参数。
class RequestDTO{
String responsableServicio;
public String getResponsableServicio() {
return responsableServicio;
}
public void setResponsableServicio(String responsableServicio) {
this.responsableServicio = responsableServicio;
}
}
将 Controller 写为
@PostMapping(path = "/getCountAnexos")
@ResponseBody
public String countAnexosRechazo(@RequestBody RequestDTO responsableServicio) {
Map<String, Object> json = new HashMap<String, Object>();
// Cambiar a nativeQuery
System.out.println("*******************************************");
System.out.println("*******************************************");
System.out.println(responsableServicio.getResponsableServicio());
System.out.println("*******************************************");
System.out.println("*******************************************");
String respuesta = formularioRepository.getAnexosRechazados(responsableServicio.getResponsableServicio());
System.out.printf("RESPUESTA",respuesta);
return respuesta;
}
那会很好的..!!
如果这也不起作用,
1)检查您导入的@Query应该来自org.springframework.data.jpa.repository.Query
2)检查Repository接口(interface)是否有@Repository注解。
3)检查@Param是否从org.springframework.data.repository.query.Param
导入
关于java - Spring Boot 中的 JPA native 查询中未设置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61509788/