【问题标题】:Legacy mapping with hibernate使用休眠的旧版映射
【发布时间】:2010-10-10 23:55:36
【问题描述】:

对于我当前的项目,我必须使用 hibernate 映射一个遗留数据库,但我遇到了一些问题。 数据库是使用一个“实体”表设置的,该表包含所有域对象的公共属性。属性包括(除其他外)创建日期、所有者(用户)和随后在表中用于域对象的主键。

上下文的简单表示如下:

table entity
 - int id
 - varchar owner

table account
 - int accountid (references entity.id)

table contact
 - int contactid (references entity.id)
 - int accountid (references account.accountid)

当我尝试将集合映射添加到我的帐户映射时,我的问题出现了,其中包含属于该帐户的所有联系人。我的尝试归结为以下几点:

<hibernate-mapping>
    <class name="Contact" table="entity">
        <id name="id" column="id">
            <generator class="native" />
        </id>
        <join table="contact">
            <key column="contactid"/>
            <!-- more stuff -->
        </join> 
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="Account" table="entity">
        <id name="id" column="id">
            <generator class="native" />
        </id>


        <bag name="contacts" table="contact">
            <key column="accountid" />
            <one-to-many class="Contact"/>
        </bag> 

        <join table="account">
            <key column="accountid"/>
            <!-- more stuff -->
        </join>

    </class>
</hibernate-mapping>

但是,当我尝试获取帐户时,我收到一条 SQL 错误,指出实体表不包含名为 accountid 的列。我明白为什么会这样:当我希望它在联系人表中查找时,映射会尝试在实体表中查找 accountid 列。我在这里遗漏了一些明显的东西,还是应该从另一个方向解决这个问题?

【问题讨论】:

    标签: java hibernate mapping


    【解决方案1】:

    在我看来,您实际上需要使用 Table Per Subclass 范例来映射继承。

    类似这样的:

    <class name="entity" table="entity">
        <id name="id" column="id">
            ...
        </id>
    
        <joined-subclass name="contact" table="contact">
            <key column="contactid"/>
        </joined-subclass>
    
        <joined-subclass name="account" table="account">
            <key column="accountid"/>
        </joined-subclass>
    </class>
    

    顺便说一句,这是近似值 - 在 Hibernate 文档的第 9.1.2 节中有详细描述(以防万一您找不到它,它被称为“每个子类的表”)。

    干杯

    丰富

    【讨论】:

    • 继承部分的完整确认。
    • 我倾向于接受这个答案。但是,我首先在等待更多回复,我讨厌接受然后不接受答案。至少 +​​1 ;-)
    猜你喜欢
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 2011-06-11
    相关资源
    最近更新 更多