Hibernate学习笔记(六)【映射继承关系】
场景有个User类,然后扩展出了Student类和Teacher类,也就是Student类和Teacher类继承了User类
<class name="User"abstract="true">
<id name="id" column="USER_ID" type="long">
<generator column="USER_NAME" type="string"></property>
<union-subclass name="Teacher" table="TEACHER">
<property name="job" column="TEACHER_JOB"/>
</union-subclass>
<union-subclass name="Student" table="STUDENT">
<property name="class" column="STUDENT_CLASS"/>
</union-subclass>
</class>
用法就是存储查询Teacher、Student都可以;如果查全的也行User,数据库发的是union语句
尼玛整个各种子类和他们的父类都在一张表,同时搞个字段区分是哪个类。配置文件这么写:
<class name="User"table="USERS">
<id name="id" column="USER_ID" type="long">
<generator type="String"></discrimnator>
<property name="name" column="USER_NAME" type="string"></property>
<subclass name="Teacher" discrimnator-value="TEACHER">
<property name="job" column="TEACHER_JOB"/>
</subclass>
<subclass name="Student" discrimnator-value="STUDENT">
<property name="class" column="STUDENT_CLASS"/>
</subclass>
</class>
父类如果不是抽象类,也可以在<class>表情内部搞个discrimnator-value="某某",这样父类子类任意搞
父类对应一张表,每子类再各自对应一张表,子类表的主键也是外键,就是说子类id=2,和父类里面有个id=2的组合用,多了个key配。配置文件这么写的:
<class name="User"table="USERS">
<id name="id" column="USER_ID" type="long">
<generator column="USER_NAME" type="string"></property>
<joined-subclass name="Teacher" table="TEACHER">
<key column="TEACHER_ID"/>
<property name="job" column="TEACHER_JOB"/>
</joined-subclass>
<joined-subclass name="Student" table="STUDENT">
<key column="STUDENT_ID"/>
<property name="class" column="STUDENT_CLASS"/>
</joined-subclass>
</class>
?
区别嘛,都标红了,数据库的区别,可以看看标红的类对应表没,至于用哪种,你觉得用起来哪种舒服就那种。有时候都不搞继承,当字段区分搞了。