类之间具有继承关系,但是数据库中的关系模型并不支持继承和多态。
那么hibernate如何支持类之间的继承关系呢?
有一种最简单的映射方式是 继承关系树的每个具体类对应一个表:关系数据模型完全不支持域模型中继承关系和多态。
下面有三个类:员工类(Employee),小时工(HourEmployee),薪资员工(SalaryEmployee)。小时工和薪资员工继承自员工类。
package com.shizhan.po;
public class Employee {
private Long id ;
private String name ;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
HourEmployee类:
package com.shizhan.po;
public class HourEmployee extends Employee{
private double rate ;
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
}
SalaryEmployee类:
package com.shizhan.po;
public class SalaryEmployee extends Employee{
private double salary ;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
每个类对应一个映射文件:
HourEmployee.hbm.xml
<?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>
<class name="com.shizhan.po.HourEmployee" table="houremployee">
<id name="id" type="java.lang.Long">
<generator class="increment" />
</id>
<property name="name" type="java.lang.String"/>
<property name="rate" type="double"/>
</class>
</hibernate-mapping>
SalaryEmployee.hbm.xml
<?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>
<class name="com.shizhan.po.SalaryEmployee" table="salaryemployee">
<id name="id" type="java.lang.Long">
<generator class="increment" />
</id>
<property name="name" type="java.lang.String"/>
<property name="salary" type="double"/>
</class>
</hibernate-mapping>
测试数据:查询的时候可以 使用 from Emolyee 语句,hql语句支持多态查询,查询的是 Employee类及其子类的数据。
Session session = DBUtil.getSession();
//不能写from Employee,因为Employee没有映射,所以只能写全称类名
//from Employee是多态查询,查询的employee是employee及其子类
String hql = "from com.shizhan.po.Employee" ;
Query query = session.createQuery(hql);
List<Employee> list = query.list();
for(Employee e : list)
{
System.out.println(e.getClass());
System.out.println( e.getName() );
}