如何使用 hibernate/jpa 注释将一个类映射到不同的表

问题描述:

我目前被困在一个看似非常简单的问题上,但我似乎无法找到解决方法:

I'm currently stuck with what seems to be a very simple problem, but I just can't seem to find a way around:

我有 2 个 相同的 表:

  1. tbl_creditcard_approved_txns
  2. tbl_creditcard_declined_txns

两者中的字段是相同的,我有一个类 - Transaction 用于表示表格中的所有适当字段.

The fields in both are identical, and I have one class - Transaction that is used to represent all the appropriate fields in the tables.

我正在尝试将两个不同的实体(每个表一个)映射到上述类.在旧世界中,我会创建两个 hbm.xml 文件,每个表一个,并将它们都映射到 Transaction.然后,我会在持久化期间使用实体名称,以确保对象在正确的表中持久化,具体取决于具体情况.

I'm trying to map two different entities (one for each table) to the above class. In the old world, I'd have created two hbm.xml files, one for each table and map both of them to Transaction. I'd then use the entity name during persistence to ensure that the object gets persisted in the correct table, depending on the circumstance.

我目前正在尝试使用注释来实现相同的目的,但到目前为止还没有成功将 2 个实体映射到 单个 类.这可能吗?

I am trying to use annotations currently to achieve the same but have had no luck so far in mapping the 2 entities to a single class. Is this possible at all?

我目前正在使用一种不同的方法,因为我已将所有公共字段(相同的列名)提取到一个 @MappedSuperClass 中,并创建了两个单独的类(每个实体一个)从超类扩展(这些类只有相同的字段,但列名不同,如果适用).

I'm currently using a different approach in that I've extracted all the common fields (identical column names) into an @MappedSuperClass and have created two separate classes (one for each entity) that extend from the super class (these classes just have the same fields with different column names, where applicable).

使用@MappedSuperclass,您将进行如下操作:

Using @MappedSuperclass, you would proceed as follows:

@MappedSuperclass
public class Transaction ...

@Entity
@Table(name="tbl_creditcard_approved_txns")
public class DeclinedTransaction extends Transaction ...

@Entity
@Table(name="tbl_creditcard_declined_txns")
public class ApprovedTransaction extends Transaction ...

如果需要,使用@AttributeOverride 覆盖两种类型的 Transaction 对象之间的列名称.

Use @AttributeOverride to override column names between the two types of Transaction objects, if needed.

更新:我看到您想将一个 @Entity 映射到同一个 EntityManagerFactory 中的两个表......我认为您不能这样做.

Update: I see that you want to map one @Entity to two tables in the same EntityManagerFactory ... I don't think you can do that.