iT邦幫忙

0

Hibernate的oneToMany與ManyToOne的意義

以下的程式,有City跟Country兩個類別,city跟country是多對一的關係,

程式可以正常運作:

City類別:

public class City {
        private int cityId;
        private String cityName;
        private Country country;
......
}

City的映射檔:

<hibernate-mapping package="com.test.vo">
        <class name="City" table="CITY">
                <id name="cityId" column="CITY_ID">
                        <generator class="increment"/>
                </id>
                <property name="cityName" column="CITY_NAME" />

<many-to-one name="country" column="COUNTRY_ID" class="com.test.vo.Country"
cascade="all"/><!--country是外鍵屬性、COUNTRY_ID是外鍵欄位-->
        </class>
</hibernate-mapping>

Country類別:

public class Country {
        int countryId;
        String countryName;
        String countyCreateDate;

        private Set<City> cities =new HashSet<City>();

......
}

Country映射檔:

<hibernate-mapping package="com.test.vo">
        <class name="Country" table="COUNTRY">
                <id name="countryId" column="COUNTRY_ID">
                        <generator class="sequence">
                                <param name="sequence">country_id_seq</param>
                        </generator>
                </id>
                <property name="countryName" column="COUNTRY_NAME" />
                <property name="countyCreateDate" column="COUNTRY_CREATE_DATE"
 />

        <set name="cities" table="city" cascade="all">
            <key column="country_Id"/><!--country_Id是外鍵欄位-->
            <one-to-many class="com.test.vo.City"/>
        </set>
        </class>
</hibernate-mapping>

雖然程式可以正常運行,但我不懂的是映射檔有關many-to-one tag以及set tag的部分,為何這樣設定外鍵欄位跟外鍵屬性

即可正常執行crud

背後的邏輯是什麼?希望可以搞懂,不然又變成只是死背語法了。

尚未有邦友回答

立即登入回答