How to map one class to different tables using hibernate/jpa annotations

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

I have 2 identical tables:

  1. tbl_creditcard_approved_txns
  2. tbl_creditcard_declined_txns

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

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.

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?

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).

11
задан Pascal Thivent 17 August 2010 в 23:20
поделиться

3 ответа

Другой способ сделать это - использовать разделенную таблицу на уровне базы данных, которая затем сделает видимой одну таблицу для вашего код Java.

Это, вероятно, правильный путь, как правило, чем более умное разбиение вы делаете, тем быстрее могут быть ваши запросы.

2
ответ дан 3 December 2019 в 04:51
поделиться

Вы должны использовать две разные единицы сохранения состояния или две отдельные сущности. Ответ на этот вопрос уже был здесь .

2
ответ дан 3 December 2019 в 04:51
поделиться

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 ...

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

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.

19
ответ дан 3 December 2019 в 04:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: