1. 程式人生 > >hibernate one2many (雙向關聯)

hibernate one2many (雙向關聯)

gif pro ng- utf-8 getc div sed .class blog

跟單向關聯僅有幾處不同:

1從多的一方加入新的屬性

package com.cnblogs.hibernate_first;

public class Student {

    private int id;

    private String name;
    
    private Classes classes;

    public Classes getClasses() {
        return classes;
    }

    public void setClasses(Classes classes) {
        this.classes = classes;
    }

    
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

2修改xml文件.Classes.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" > <hibernate-mapping package="com.cnblogs.hibernate_first"> <class name="Classes" table="t_classes"> <id name="id" column="t_id"> <generator class="native"></generator> </id> <property name="name" column="t_name" length="30"/> <!-- 將set student加入inverse 屬性設為true ,則表示該字段放棄對多的一方的管理,表示從一的一方添加失效 --> <set name="students" inverse="true"> <key column="classesid"></key> <one-to-many class
="com.cnblogs.hibernate_first.Student"/> </set> </class> </hibernate-mapping>

3,修改Student.hbm.xml文件

技術分享
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >

<hibernate-mapping package="com.cnblogs.hibernate_first">
    <class name="Student" table="t_student">
        <id name="id" column="t_id">
            <generator class="native"></generator>
        </id>
        <property name="name" column="t_name" length="30"/>
        <many-to-one name="classes" column="classesid"></many-to-one>
    </class>
</hibernate-mapping>
View Cod

hibernate one2many (雙向關聯)