![](/img/trans.png)
[英]How to receive a set from Spring Data JPA NativeQuery? [results in NotReadablePropertyException]
[英]How to replace table name with parameter value while using Spring Data JPA nativeQuery
像这样:
public interface XXXRepository extends CrudRepository<XXX, Integer> {
@Query(value = "select * from ?1 where ...", nativeQuery = true)
List<XXX> findByXXX(String tableName, ...);}
它在代码上给出了 MYSQL 语法错误。 语法错误显示SQL中表名被“'”包围。
这不可能。 参数只允许在 where 子句中。
如果您使用的是 Spring Data 存储库,则可以使用#{#entityName}
SpEL 表达式作为实体名称的占位符。 根据您的用例,不再需要使用实体名称作为方法参数。
当您使用nativeQuery = true
时,我不确定此功能是否nativeQuery = true
请参阅此处的文档: https : //docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.query.spel-expressions
您可以在 JPA 项目中使用EntityManager
。
@Autowired
EntityManager entityManager;
Query createQuery(String tableName) {
return entityManager.createNativeQuery("select * from " + tableName);
}
我有一个解决方法。
它使用 javax.persistence.EntityManager 和 String.format 来做到这一点。
package com.example.test.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import javax.persistence.EntityManager;
@Component
public class SomeDao {
@Autowired
EntityManager em;
public List<?> listFoodMoneyDateOfPayment(int departmentId, String sumKey, String tableName) {
String s = "SELECT SUM(%s) AS money, CONCAT(YEAR(apply_time), '-', MONTH(apply_time)) AS yearmonth " +
"FROM (%s) WHERE department_id = %d GROUP BY yearmonth";
String sql = String.format(s, sumKey, tableName, departmentId);
System.out.println(sql);
List<?> test = em.createNativeQuery(sql).getResultList();
return test;
}
}
调用代码是:
@RestController
@RequestMapping("/api")
public class TestController {
@Autowired
private SomeDao dao;
@RequestMapping("/test2")
public HttpEntity test2() {
var l = dao.listFoodMoneyDateOfPayment(12, "food_payment", "payment_application");
System.out.println(l.getClass());
System.out.println(JSON.toJSONString(l));
return ResultBean.success();
}
}
它运作良好。
但是你应该检查传入的参数。
这可以通过 jdbc 实现:
@Autowired
JdbcTemplate jdbcTemplate;
public String nativeQueryToString(String query) {
try {
return jdbcTemplate.queryForObject(query, String.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.