Java 在@Table(name = "tableName") 中 - 使“tableName”成为 JPA 中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2444962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:46:28  来源:igfitidea点击:

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

javajpaejb-3.0

提问by zengr

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

我正在使用 JPA,我需要将“tableName”设为变量。

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

在一个数据库中,我有很多表,我的代码需要访问我指定要读取的表。

@Entity
@Table(name = "tableName")
public class Database implements Serializable {...............}

Any ideas?

有任何想法吗?

采纳答案by Adeel Ansari

You can do something like this, if thats your concern, I guess. Never tried it, its just a wild guess. But thats the usual practice -- I follow for Named Queries; yes, that's a different thing altogether.

你可以做这样的事情,如果那是你的问题,我想。从未尝试过,这只是一个疯狂的猜测。但这是通常的做法——我遵循命名查询;是的,那完全是另一回事。

@Entity
@Table(name = Database.tableName)
public class Database implements Serializable {
    public static final String tableName = "TABLE_1";
    ...............
}

But I don't see why anyone would do that. Could you tell us what are you up to? Why you have few tables exactly same definition?

但我不明白为什么有人会这样做。你能告诉我们你在做什么吗?为什么你有几个表完全相同的定义?

[Edited]

[编辑]

I tried your solution. It did not work, it says: The value for annotation attribute Table.name must be a constant expression.

我试过你的解决方案。它不起作用,它说:注释属性 Table.name 的值必须是一个常量表达式。

So, isn't that clear enough? I mean you can't do that. And I believe its quite logical. If you want Hibernate to generate your schema then you can define all the entities you want, in the schema, and with the appropriate relationships.

那么,这还不够清楚吗?我的意思是你不能那样做。我相信它很合乎逻辑。如果您希望 Hibernate 生成您的架构,那么您可以在架构中定义您想要的所有实体,并使用适当的关系。

回答by Pascal Thivent

Specifying the table name at runtime is not possible, this is simply not how JPA works (and I'm still not sure to get your requirement). Either map different entities on your set of tables and run various queries or build them dynamically (maybe using the Criteria API) depending on the input from the client side oruse something else than JPA (like iBATIS).

在运行时指定表名是不可能的,这根本不是 JPA 的工作方式(我仍然不确定是否满足您的要求)。要么在您的一组表上映射不同的实体并运行各种查询,要么根据来自客户端的输入动态构建它们(可能使用 Criteria API),或者使用 JPA 以外的其他内容(如 iBATIS)。

回答by Andrei I

If you want only to reference/read the table name, it is possible as in the code below. If you want to change, it is not possible as Pascal said.

如果您只想引用/读取表名,则可以如下面的代码所示。如果你想改变,不可能像帕斯卡所说的那样。

@Entity
@Table(name = Database.tableName)
public class Database implements Serializable {
    public static final String tableName = "TABLE_1";//this variable you can reference in other portions of your code. Of course you cannot change it.
    ...............
}

回答by Alex85

If you want to select data from different tables,

如果要从不同的表中选择数据,

then you can use :

那么你可以使用:

@Subselect("")

@Subselect("")

instead of :

代替 :

@Table(name = "tableName").

@Table(name = "tableName").

回答by HumbertZhang

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.

它运作良好。
但是你应该检查传入的参数。