这个表是按月生成的。基本上所有monthly表的表结构都是一样的。
因为用不同的表名映射同一个实体会做很多工作,
是否可以在运行时更改实体的表名,因为它们毕竟具有相同的表结构?
@Entity
@Table(name="FOO_JAN2010") // any other ways to generate this dynamically?
public class FooJan2010Table { // if we can dynamically set the table name this can be simply named FooTable
...
}
如果没有,您可以建议什么方法?
最佳答案
Is it possible to change the table name of an entity as follows on runtime since they have the same table structure after all?
这实际上是不可能的,至少对于标准 JPA(这并不意味着我使用非标准 JPA 这样做)是不可能的,如以下问题所述:
- In @Table(name = “tableName”) - make “tableName” a variable in JPA
- JPA: How do I specify the table name corresponding to a class at runtime?
- Hibernate or iBatis or something else?
总而言之,JPA 不提供“更改”已初始化持久性单元的给定实体(以及相关的预编译 CRUD 查询、预编译命名查询等)的方法。
不过,既然您使用的是 Hibernate,不妨看看 http://www.hibernate.org/171.html了解使用 Hibernate Core API 的可能性。
我能想到的另一个选择是使用数据库 synonym/alias:FOO
将是 FOO_JAN2010 的别名
直到...您将别名更改为指向 FOO_FEB2010
。我从来没有测试过这个,我不知道它是否适合你的需求。但这是另一个想法。
关于java - 在运行时更改实体的表名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3879607/