Hibernate使用hbm.xml将多个类映射到一个表

时间:2012-01-05 06:59:42

标签: java hibernate java-ee mapping hibernate-mapping

我是Hibernate的新手,需要一些hibernate-mapping的帮助。

我有4个不同的类要映射到一个表中,其中主键由2个不同类的属性组成。同时,我想只将每个类的选定属性映射到本地数据库。我希望避免使用JPA注释,而是在hbm.xml文件中定义映射样式。我该怎么做?

采用以下示例:

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
}

最终表应包含以下内容:

    type | rackLabel | circuitNo | date | kva | current | energy

上面的“circuitNo”和“date”应该构成复合主键。

有人能告诉我一个如何映射这个的例子吗?谢谢!

2 个答案:

答案 0 :(得分:2)

Hibernate提供了一种使用discriminator关键字映射子类的方法。

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

答案 1 :(得分:0)

没有什么可以阻止你这样做。创建4个指向同一个表但不同Pojos的HBM。虽然可以做到,如@Ioan Alexandru Cucu,但不建议这样做。

   <!-- HBM1-->

<class name="com.myProject.Rack"
    table="My_Table">

   <!-- HBM2-->

   <class name="com.myProject.Rack"
    table="My_Table">