Hibernate mapping multiple classes to one table using hbm.xml
10,680
Hibernate provide a way to map subclass using discriminator keyword.
<class name="Payment" table="PAYMENT">
<id name="id" type="long" column="PAYMENT_ID">
<generator class="native"/>
</id>
<discriminator column="PAYMENT_TYPE" type="string"/>
<property name="amount" column="AMOUNT"/>
...
<subclass name="CreditCardPayment" discriminator-value="CREDIT">
<join table="CREDIT_PAYMENT">
<key column="PAYMENT_ID"/>
<property name="creditCardType" column="CCTYPE"/>
...
</join>
</subclass>
<subclass name="CashPayment" discriminator-value="CASH">
<join table="CASH_PAYMENT">
<key column="PAYMENT_ID"/>
...
</join>
</subclass>
<subclass name="ChequePayment" discriminator-value="CHEQUE">
<join table="CHEQUE_PAYMENT" fetch="select">
<key column="PAYMENT_ID"/>
...
</join>
</subclass>
</class>
Author by
louis xie
Updated on June 04, 2022Comments
-
louis xie almost 2 years
I am fairly new to Hibernate and need some help with hibernate-mapping.
I have 4 different classes which I want to map into one table, of which the primary key consists of attributes from 2 different classes. At the same time, I want to map only selected attributes from each class into a local database. I wish to avoid JPA annotations and define the mapping style in a hbm.xml file instead. How do I do that?
Take the following example:
public class Tenant implements Serializable { private final static long serialVersionUID = 1L; protected List<Rack> rack; protected String type; //getters setters } public class Rack implements Serializable { private final static long serialVersionUID = 1L; protected List<Circuit> circuit; protected String rackLabel; protected Boolean excludes; //getters setters } public class Circuit implements Serializable { private final static long serialVersionUID = 1L; protected List<CircuitReadings> circuitReadings; protected String circuitNo; protected Boolean excludes; //getters setters } public class CircuitReadings implements Serializable { private final static long serialVersionUID = 1L; protected String date; protected String kva; protected String current; protected String kwh; //getters setters }
And the eventual table should consist of the following:
type | rackLabel | circuitNo | date | kva | current | energy
"circuitNo" and "date" above should form the composite primary keys.
Can someone show me an example of how I should map this? Thanks!
-
louis xie over 12 yearsI'm trying to understand how this would work. Referring back to my example,, how do I specify in the hbm that I want to repeat the same "circuitNo" for each "date", "kva", "current", and "energy" in the "CircuitReadings" list?