《二》每个子类映射到一张表(joined-subclass)
配置文件修改为:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="hibernate.extend" auto-import="false">
<class name="Person" table="person" >
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="age"/>
<joined-subclass name="Worker" table="worker" >
<key column="person_id"></key> //指定外键关联的列
<property name="work_year"/>
</joined-subclass>
<joined-subclass name="Farmer" table="farmer" >
<key column="person_id"/> //指定外键关联的列
<property name="farm_name"/>
</joined-subclass>
</class>
</hibernate-mapping>
上面的配置中,我们并没有单独为worker和farmer编写映射文件,而是通过joined-subclass节点在父类映射文件中对子类进行了配置。
仍然执行上面的测试代码,查看输出的sql语句为:
这时数据库中就有三张表了,分别为:person表,worker表,farmer表。结构如下:
person:
+----+--------+------+
| id | name | age |
+----+--------+------+
| 1 | person | 22 |
| 2 | worker | 30 |
| 3 | farmer | 31 |
+----+--------+------+
worker:
+-----------+----------------+
| person_id | work_year |
+-----------+----------------+
| 2 | 11 |
+-----------+----------------+
farmer:
+-----------+-----------------+
| person_id | farm_name |
+-----------+-----------------+
| 3 | little candy |
+-----------+-----------------+
查询:
static void query(int id) { Session s = HibernateUtil.getSession(); Transaction tx = s.beginTransaction(); Worker worker = (Worker) s.get(Worker.class, id); tx.commit(); System.out.println("year: "+worker.getWork_year()); }
调用query(2);
打印输出的sql语句为:
如果把着色部分修改为:Worker worker = (Worker) s.get(Person.class , id);
打印输出的sql语句为:
由此可见:hibernate支持多态查询。在查询语句中,指定父类类型,hibernate会关联三张表到其中去查,而指定了具体的类型,则只会查找相关的表。如果子类有很多,那么最好明确指定查的子类,否则,对多表关联查询,会带来性能问题。