How to replace table name with value from parameter while using Spring Data JPA nativeQuery

前端 未结 4 2058
醉梦人生
醉梦人生 2020-12-02 01:32

like this:

public interface XXXRepository extends CrudRepository {
@Query(value = \"select * from ?1 where ...\", nativeQuery = true)
Lis         


        
相关标签:
4条回答
  • 2020-12-02 01:59

    I have a workaround.
    It uses javax.persistence.EntityManager and String.format to do that.

    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.

    0 讨论(0)
  • 2020-12-02 02:01

    You can use entitymanger in jpa project.

    @Autowired EntityManager entityManager;

    entityManager.createNativeQuery("select * from "+tableName+"")

    0 讨论(0)
  • 2020-12-02 02:13

    This is not possible. Parameters are only allowed in the where clause.

    0 讨论(0)
  • 2020-12-02 02:13

    If you are using a Spring Data repository, you can use #{#entityName} SpEL expression as a placeholder for the entity name. 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

    See the documentation here: https://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#jpa.query.spel-expressions

    0 讨论(0)
提交回复
热议问题