简体   繁体   English

使用Spring Data JPA nativeQuery时如何用参数值替换表名

[英]How to replace table name with parameter value while using Spring Data JPA nativeQuery

like this:像这样:

public interface XXXRepository extends CrudRepository<XXX, Integer> {
@Query(value = "select * from ?1 where ...", nativeQuery = true)
List<XXX> findByXXX(String tableName, ...);}

It gives MYSQL syntax error with upon codes.它在代码上给出了 MYSQL 语法错误。 The syntax error shows that the table name in the SQL is surrounded with "'".语法错误显示SQL中表名被“'”包围。

This is not possible.这不可能。 Parameters are only allowed in the where clause.参数只允许在 where 子句中。

If you are using a Spring Data repository, you can use #{#entityName} SpEL expression as a placeholder for the entity name.如果您使用的是 Spring Data 存储库,则可以使用#{#entityName} SpEL 表达式作为实体名称的占位符。 Depending on your use case, it is not necessary to use the entity name as method parameter anymore.根据您的用例,不再需要使用实体名称作为方法参数。

I am not sure if this feature works when you use nativeQuery = true当您使用nativeQuery = true时,我不确定此功能是否nativeQuery = true

See the documentation here: https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.query.spel-expressions请参阅此处的文档: https : //docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.query.spel-expressions

You can use EntityManager in JPA project.您可以在 JPA 项目中使用EntityManager

   @Autowired
   EntityManager entityManager;

   Query createQuery(String tableName) {
       return entityManager.createNativeQuery("select * from " + tableName);
   }

I have a workaround.我有一个解决方法。
It uses javax.persistence.EntityManager and String.format to do that.它使用 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;
    }
}

The invoke code is that:调用代码是:

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

And it works well.它运作良好。
But you should check the arguments passed in.但是你应该检查传入的参数。

This is possible with jdbc:这可以通过 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.

相关问题 如何从Spring Data JPA NativeQuery接收集合? [导致NotReadablePropertyException] - How to receive a set from Spring Data JPA NativeQuery? [results in NotReadablePropertyException] Spring Data JPA @Query注释,nativeQuery = true, - Spring Data JPA @Query annotation, nativeQuery = true, Spring data JPA nativeQuery order by 无效 - Spring data JPA nativeQuery order by is invalid 有没有办法在使用 Spring Data JPA 的查询中使用列名作为参数? - Is there a way to use column name as a parameter in a query using Spring Data JPA? 具有两个输出参数的Spring-data-jpa NativeQuery - Spring-data-jpa NativeQuery with two output params 列名称作为Spring Data JPA查询的参数 - Column name as a parameter to Spring Data JPA Query 无法在springboot和Data JPA中使用nativeQuery方法访问数据记录 - Can not accessing data records using nativeQuery method in springboot and Data JPA 如何在Spring Data JPA中使用After和Equals创建方法名称? - How to create method name using After and Equals in Spring Data JPA? 如何在不使用 nativeQuery 的情况下在 JPA 上转换它? - How can I convert this on JPA without using nativeQuery? 如何使用 SqlResultSetMapping 将 JPA NativeQuery 的结果集映射到 POJO - How to map the result set of a JPA NativeQuery to a POJO using SqlResultSetMapping
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM