Spring Boot中的JPA Native Query中未设置参数



我正在Spring Boot中开发后端,我将JPA用于所有DB操作。问题如下:

我从前端收到一个名为"responsableServicio"的参数,首先它到达我检查参数的控制器方法。但是,当参数从控制器转到存储库时,值没有得到正确的值,它似乎是空的,因为我的查询应该返回1条记录,而返回0条记录。

我想强调的是,如果将参数硬编码在查询中,它将返回正确的结果1。

我举了一些例子,但还没有奏效。我做错了什么?提前感谢

Formulario控制器

@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;
}

Formulario存储库

// 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);

我从控制台得到什么

img

问题出在控制器类中。它将String作为带括号的完整JSON。在这里,您使用了一个@PostMapping,并使用@RequestBody String responsableServicio作为方法参数。不能将String作为类型参数,必须创建一个类,该类将String responsableServicio作为变量,并带有getters/ssetter。然后在控制器中,将参数作为类参数。

class RequestDTO{
String responsableServicio;
public String getResponsableServicio() {
return responsableServicio;
}
public void setResponsableServicio(String responsableServicio) {
this.responsableServicio = responsableServicio;
}
} 

将控制器写入

@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接口是否具有@Repository注释。

3( 检查@Param是否从org.springframework.data.repository.query.Param导入

最新更新