开发者

Many-to-one relationship in Hibernate

I would like to establish a relationship many-to-one between two fields on database. I am using PostgreSQL database and Hibernate. The tables are ApplicationField and Device. The first one has 2 columns: AppFieldId and Name. The second one has NodeId, Description and AppFieldId. The hibernate mapping for ApplicationField is:

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

And for Device:

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

On Java classes I have a List devices on ApplicationField class and ApplicationField appField on Device class. However, when 开发者_C百科I try to create a sessionFactory, I obtain an exception like:

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

How should I do the relationship between the tables?

Thanks a lot!!


I guess the relationship is as follow:

One ApplicationField has many Devices.
One Device can refer to Many ApplicationField.

If It is true, then there are some mistakes in your mapping.

Replace devices set with following (change in Id column):

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

Update many-to-one mapping as:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜