JPA Hibernate - Mapping Embedded Collections to a Single Table

守給你的承諾、 提交于 2021-02-08 05:57:34

问题


I have a table with lot of fields such as

Account

OrderNo

Term

LegNo

LegSymbol

LegSymbolType

LegExchangeType

etc etc

The primary key of the above table is a composite key comprising of Account, OrderNo & LegNo

The data in the DB would look something like this

1234 1 2 1 AAA BBB CCC

1234 1 2 2 DDD EEE FFF

The bolded ones are Account,Order,LegNo respectively.

While designing the entity for the above table, we want to group all the Leg related information (All bolded columns ) in a separate class and all other info in a entity

So, the main Order Entity will contain the Embedded object Leg. (I assume Leg wont be defined as an entity since it is not a separate table as such).

@Entity
@Table(name="xxx")
public class Order implements Serializable {

    ... All order specific fields & it's getters/setters

}

@Embeddable
public class Leg implements Serializable {

  private long legNo;
  private String legSymbol;

  ...
  ...
}

I assume Order Entity would hold the account, orderNo,Term info and the OrderLeg embedded object would the other info like the above.

We can have multiple legs for the same order as shown in the above record. Hence we might need to have collection of legs inside the Order entity.

Can we achieve this functionality as we have only one table in place ? We cannot change the schema of the table or create a new table as it is out of our control.

I tried using the @ElementCollection in the Order Entity on List of Legs but it looks like, when I try to persist a new order, the Leg details are not being taken as part of the query.

If I have hibernate.hbm2ddl.auto=create as part of the persistence.xml, it deletes the existing schema and alters the existing order table to hold only the order infos and creates a separate leg table to hold the leg infos which is not desired.

@Entity
@Table(name="xxx")
public class Order implements Serializable {

**@ElementCollection
private List<Leg> a = new ArrayList<Leg>();**
}

The values set to Leg class such as LegNo, LegSymbol etc is not included in the insert query at all and I always get an exception since the LegNo is a mandatory field in the table.

Please advise..

来源:https://stackoverflow.com/questions/21769860/jpa-hibernate-mapping-embedded-collections-to-a-single-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!