首页 > 代码库 > hibernate中的cascade和inverse

hibernate中的cascade和inverse

以Student和class为例,一个Student对应一个class,一个class对应多个Student。

Student.hbm.xml

<?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 2016-11-19 9:05:48 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.hibernate4.model.Student" table="t_student">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>
        <many-to-one name="c" class="com.hibernate4.model.Class" cascade="save-update">
        <!--  cascade="save-update"表示保存Student时也保存class -->
            <column name="classId" />
        </many-to-one>
    </class>
</hibernate-mapping>

class.hbm.xml

<?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 2016-11-19 9:05:48 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
    <class name="com.hibernate4.model.Class" table="t_class">
        <id name="id" type="long">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" />
        </property>

        <set name="students" inverse="true" cascade="delete">
            <!-- inverse="true"表示由双向关系中的另一方维护,即增加一个student时,如果Student的class属性目前在class表中 
                不存在,那么可以马上新增这个class -->
                <!-- cascade="delete"表示当删除一个class时,与之相关联的所有Student数据同时删除 -->
            <key column="classId"></key>
            <one-to-many class="com.hibernate4.model.Student" />
        </set>
    </class>
</hibernate-mapping>

 

hibernate中的cascade和inverse