In @Table(name = “tableName”) - make “tableName” a variable in JPA

后端 未结 5 1402
無奈伤痛
無奈伤痛 2020-12-16 14:35

I am using JPA and I need to make the \"tableName\" a variable.

In a database, I have many tables, and my code needs to access the table where I specify it to read.

5条回答
  •  甜味超标
    2020-12-16 15:27

    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.

提交回复
热议问题