<!-- 类继承树的映射配置--> <hibernate-mapping package="com.mr.person"> <class name="Person" table="tab_person"> <id name="id"> <generator class="native"/ > </id> <!-- 声明一个鉴别器--> <discriminator column="type" type="String"/ > <!-- 映射自有属性--> <property name="name" not-null="true"/ > <property name="age" type="int"/ > <property name="sex" type="string"/ > <!-- 声明子类 --> <subClass name="student" discriminator-value="学生"> <property name="school"> </subClass> <subclass name="staffer" discriminator-value="职员"> <property name="company"> </subclass> </class> </hibernate>
//Hibernate的持久化操作 session = HibernateInitialize.getsession(); session.beginTransaction(); //事物开启
Student student = new Student(); student.setName("小明"); student.setAge("12"); student.setSex("男"); student.setSchool("明日希望小学"); session.save(student);
Staffer staffer = new Staffer("小红", 25, "女"); staffer.setCompany("明日科技"); session.save(staffer);
session.getTransaction().commit(); //事物提交
<!-- 每个子类的映射配置--> <hibernate-mapping package="com.mr.person"> <class name="Person" table="tab_person"> <id name="id"> <generator class="native"/ > </id> <!-- 声明一个鉴别器--> <discriminator column="type" type="String"/ > <!-- 映射自有属性--> <property name="name" not-null="true"/ > <property name="age" type="int"/ > <property name="sex" type="string"/ > <!-- 声明子类 --> <joined-subclass name="Student" table="tab_student"> <key column="id" /> <property name="school" /> </joined-subclass> <joined-subclass name="Staffer" table="tab_staffer"> <key column="id" /> <property name="company" /> </joined-subclass> </class> </hibernate>
<!-- 每个具体类的映射配置-->
<hibernate-mapping package="com.mr.person"> <class name="Person" abstract="true"> <!-- 由于父类不需要映射数据表,因此将abstract属性设置为true--> <id name="id"> <!-- 设置主键生成策略为手动分配,数据的ID需要在实体对象中的Setter方法中设定--> <generator class="assigned"/ > </id> <!-- 声明一个鉴别器--> <discriminator column="type" type="String"/ > <!-- 映射自有属性--> <property name="name" not-null="true"/ > <property name="age" type="int"/ > <property name="sex" type="string"/ > <!-- 声明子类 --> <!-- union-subclass元素,用于将具体类映射为一张表 --> <union-subclass name="Student" table="tab_student"> <property name="school" /> </union-subclass> <union-subclass name="Staffer" table="tab_staffer"> <property name="company" /> </union-subclass> </class> </hibernate>
原文:http://www.cnblogs.com/little-YTMM/p/4645745.html