【问题标题】:Many-to-one relationship in HibernateHibernate 中的多对一关系
【发布时间】:2011-09-30 04:58:51
【问题描述】:

我想在数据库的两个字段之间建立多对一的关系。我正在使用 PostgreSQL 数据库和 Hibernate。这些表是 ApplicationField 和 Device。第一个有 2 列:AppFieldId 和 Name。第二个有 NodeId、Description 和 AppFieldId。 ApplicationField 的休眠映射为:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 05-may-2011 13:21:52 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.cartif.database.ApplicationField" table="APPLICATIONFIELD">
    <id name="iAppFieldId" column="applicationfieldid" type="java.lang.Integer">
        <generator class="sequence">
            <param name="sequence">s_applicationfield</param>
        </generator>
    </id>
    <property column="name" lazy="false" name="name" type="java.lang.String"/>
    <set name="devices">
        <key column="appfieldid" />
        <one-to-many column="nodeid" class="com.cartif.zigbee.device.Device"/>
    </set>
</class>
</hibernate-mapping>

对于设备:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                               "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 07-abr-2011 13:29:19 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.cartif.zigbee.device.Device" table="Device">
    <id column="nodeid" name="iIdentifier" type="java.lang.Integer"/>
    <property column="description" generated="never" lazy="false" name="description" type="java.lang.String"/>
    <set name="appField">
        <key column="nodeid"/>
        <many-to-one column="appfieldid" class="com.cartif.database.ApplicationField"/>
    </set>
</class>
</hibernate-mapping>

在 Java 类上,我在 ApplicationField 类上有一个 List devices,在 Device 类上有一个 ApplicationField appField。但是,当我尝试创建 sessionFactory 时,我得到一个异常,例如:

org.xml.sax.SAXParseException: Attribute "column" must be declared for element type "one-to-many".

表之间的关系应该如何处理?

非常感谢!!

【问题讨论】:

    标签: hibernate one-to-many many-to-one


    【解决方案1】:

    我猜的关系如下:

    一个 ApplicationField 有许多设备。
    一个设备可以引用多个应用字段。

    如果是真的,那么你的映射中有一些错误。

    将设备集替换为以下(在 Id 列中更改):

    <set name="devices">
            <key column="applicationfieldid" />
            <one-to-many class="com.cartif.zigbee.device.Device"/>
    </set>   
    

    将多对一映射更新为:

    <many-to-one name="appField" column="applicationfieldid" class="com.cartif.database.ApplicationField"/>
    

    【讨论】:

    • 关系是:一个ApplicationField有很多Devices。一台设备只能引用一个 ApplicationField。这就像一个国家有几个城市,但一个城市只有一个国家。
    • 好吧。然后在多对一映射中使用 unique=true 。因此,只能将一个设备附加到一个 ApplicationField。
    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 2015-02-05
    • 2011-12-15
    • 2014-03-29
    • 1970-01-01
    相关资源
    最近更新 更多