JPA,如何使用同一个类(实体)来映射不同的表? [英] JPA, How to use the same class (entity) to map different tables?

查看:48
本文介绍了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 {
...
}

这篇关于JPA,如何使用同一个类(实体)来映射不同的表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆