JPA,如何使用同一个类(实体)来映射不同的表?

问题描述:

我有两个表:TaTb.它们具有完全相同的表结构但不同的表名称.

I have two tables: Ta and Tb. They have exactly the same table structure but different table names.

我尝试创建一个实体类来映射表结构.我的一些常用应用模块会使用这个实体类根据参数动态查询和更新TaTb.可以在JPA中完成吗?如何编写程序在运行时将实体类动态映射到不同的表?

I try to create one entity class to map the table structures. Some of my common application modules will use this entity class to dynamically query and update either Ta or Tb based on parameters. Can it be done in JPA? How can I write the program to dynamically mapping the entity class to different tables at run time?

不确定您是否可以完全按照自己的意愿去做,但您可以使用继承来产生相同的结果.

Not sure you can do it exactly as you want but you can use inheritance to produce the same result.

AbsT 有所有字段但没有@Table 注释

AbsT has all the fields but no @Table annotation

Ta 和 Tb 继承自 AbsT 并且每个都有一个@Table 注释

Ta and Tb inherit from AbsT and have an @Table annotation each

使用

@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

在 AbsT.

示例代码:

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class abstract AbsT {
    @Id Long id;
...
}

@Entity
@Table(name = "Ta")
public class Ta extends AbsT {
...
}

@Entity
@Table(name = "Tb")
public class Tb extends AbsT {
...
}