[標題]:[原]Hibernate繼承映射-繼承關(guān)系中每個類均映射為一個數(shù)據(jù)庫表
[時間]:2009-6-21
[摘要]:繼承關(guān)系中每個類均映射為一個數(shù)據(jù)庫表優(yōu)點:此時,與面向?qū)ο蟮母拍钍且恢碌模@種映射實現(xiàn)策略的最大好處就是關(guān)系模型完全標準化,關(guān)系模型和領(lǐng)域模型完全一致,易于修改基類和增加新的子類。缺點:數(shù)據(jù)庫中存在大量的表,為細粒度級的數(shù)據(jù)模型,訪問數(shù)據(jù)時將存在大量的關(guān)聯(lián)表的操作,效率較低。
[關(guān)鍵字]:Hibernate,ORM,關(guān)聯(lián),繼承,持久化,映射,Abstract
[環(huán)境]:MyEclipse7,Hibernate3.2,MySQL5.1
[作者]:Winty (wintys@gmail.com) http://m.tkk7.com/wintys
[正文]:
繼承關(guān)系中每個類均映射為一個數(shù)據(jù)庫表。
優(yōu)點:
此時,與面向?qū)ο蟮母拍钍且恢碌模@種映射實現(xiàn)策略的最大好處就是關(guān)系模型完全標準化,關(guān)系模型和領(lǐng)域模型完全一致,易于修改基類和增加新的子類。
缺點:
數(shù)據(jù)庫中存在大量的表,為細粒度級的數(shù)據(jù)模型,訪問數(shù)據(jù)時將存在大量的關(guān)聯(lián)表的操作,效率較低。
例:學(xué)校管理系統(tǒng)中的實體關(guān)系:

【圖:department.jpg】
1、概述
a.實體類
與allinone包中的實體類相同。
b.數(shù)據(jù)庫表
繼承關(guān)系中每個類均映射為一個數(shù)據(jù)庫表。
c.配置文件
ThePerson.hbm.xml:
......
<joined-subclass name="wintys.hibernate.inheritance.allinone.Student" table="theStudent">
<key column="id"/>
<property name="studentMajor" />
</joined-subclass>
<joined-subclass name="wintys.hibernate.inheritance.allinone.Teacher" table="theTeacher">
<key column="id" />
<property name="teacherSalary" column="teacherSalary" type="float"/>
</joined-subclass>
......
2、實體類:
Department、Person、Student、Teacher直接import wintys.hibernate.inheritance.concrete包。
3、數(shù)據(jù)庫表:

【圖:separate_db.jpg】
db.sql:
-- Author:Winty (wintys@gmail.com)
-- Date:2009-06-20
-- http://m.tkk7.com/wintys
USE db;
-- Department
CREATE TABLE mydepartment(
id INT(4) NOT NULL,
name VARCHAR(100),
descs VARCHAR(100),
PRIMARY KEY(id)
);
-- Person
CREATE TABLE thePerson(
id INT(4) NOT NULL,
name VARCHAR(100),
dept INT(4), -- 與Department關(guān)聯(lián)
PRIMARY KEY(id),
CONSTRAINT FK_dept_tp FOREIGN KEY(dept) REFERENCES mydepartment(id)
);
-- Student
CREATE TABLE theStudent(
id INT(4) NOT NULL,
studentMajor VARCHAR(100),
PRIMARY KEY(id)
);
-- Teacher
CREATE TABLE theTeacher(
id INT(4) NOT NULL,
teacherSalary FLOAT(7,2),
PRIMARY KEY(id)
);
4、映射文件:

【圖:separate_mapping.jpg】
ThePerson.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">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="wintys.hibernate.inheritance.allinone.Person" table="thePerson" catalog="db">
<id name="id" type="int">
<column name="id" not-null="true"/>
<generator class="increment" />
</id>
<property name="name" />
<many-to-one name="department"
unique="true"
column="dept"
class="wintys.hibernate.inheritance.allinone.Department"/>
<joined-subclass name="wintys.hibernate.inheritance.allinone.Student" table="theStudent">
<key column="id"/>
<property name="studentMajor" />
</joined-subclass>
<joined-subclass name="wintys.hibernate.inheritance.allinone.Teacher" table="theTeacher">
<key column="id" />
<property name="teacherSalary" column="teacherSalary" type="float"/>
</joined-subclass>
</class>
</hibernate-mapping>
hibernate.cfg.xml:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf-8
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">MySQLDriver</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="show_sql">true</property>
<mapping
resource="wintys/hibernate/inheritance/separate/ThePerson.hbm.xml" />
<mapping
resource="wintys/hibernate/inheritance/allinone/Department.hbm.xml" />
</session-factory>
</hibernate-configuration>
4、使用測試:
DAOBean.java:
package wintys.hibernate.inheritance.separate;
import wintys.hibernate.inheritance.allinone.Department;
import wintys.hibernate.inheritance.allinone.Person;
import wintys.hibernate.inheritance.allinone.Student;
import wintys.hibernate.inheritance.allinone.Teacher;
import wintys.hibernate.inheritance.concrete.DAO;
import wintys.hibernate.inheritance.concrete.HibernateUtil;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* @version 2009-06-20
* @author Winty (wintys@gmail.com)
*
*/
public class DAOBean implements DAO {
@Override
public void insert() {
Transaction tc = null;
try{
Department dept = new Department("college of math" , "the top 3 college");
Person p1,p2;
p1 = new Student("Sam" , "Math");
p1.setDepartment(dept);
p2 = new Teacher("Martin" , new Float(15000f));
p2.setDepartment(dept);
Session session = HibernateUtil.getSession();
tc = session.beginTransaction();
session.save(dept);
//多態(tài)保存
session.save(p1);
session.save(p2);
tc.commit();
}catch(HibernateException e){
try{
if(tc != null)
tc.rollback();
}catch(Exception ex){
System.err.println(ex.getMessage());
}
System.err.println(e.getMessage());
}finally{
HibernateUtil.closeSession();
}
}
@SuppressWarnings("unchecked")
@Override
public <T> List<T> select(String hql) {
List<T> items = null;
Transaction tc = null;
try{
Session session = HibernateUtil.getSession();
tc = session.beginTransaction();
Query query = session.createQuery(hql);
items = query.list();
tc.commit();
}catch(HibernateException e){
try{
if(tc != null){
tc.rollback();
items = null;
}
}catch(Exception ex){
System.err.println(ex.getMessage());
}
System.err.println(e.getMessage());
}finally{
//HibernateUtil.closeSession();
}
return items;
}
}
Test.java:
package wintys.hibernate.inheritance.separate;
import java.util.Iterator;
import java.util.List;
import wintys.hibernate.inheritance.allinone.Department;
import wintys.hibernate.inheritance.allinone.Person;
import wintys.hibernate.inheritance.allinone.Student;
import wintys.hibernate.inheritance.allinone.Teacher;
import wintys.hibernate.inheritance.concrete.DAO;
import wintys.hibernate.inheritance.concrete.HibernateUtil;
public class Test {
public static void main(String[] args) {
String config = "wintys/hibernate/inheritance/separate/hibernate.cfg.xml";
HibernateUtil.setConfigFile(config);
DAO dao = new DAOBean();
dao.insert();
//支持多態(tài)查詢
List<Person> ps = dao.select("from Person");
System.out.println(printStudentOrTeacher(ps));
//List<Student> students = dao.select("from Student");
//System.out.println(printStudentOrTeacher(students));
/*List<Student> teachers = dao.select("from Teacher");
System.out.println(printStudentOrTeacher(teachers));*/
}
public static String printStudentOrTeacher(List<? extends Person> students){
String str = "";
Iterator<? extends Person> it = students.iterator();
while(it.hasNext()){
Person person = it.next();
int id = person.getId();
String name = person.getName();
Department dept = person.getDepartment();
int deptId = dept.getId();
String deptName = dept.getName();
String deptDesc = dept.getDesc();
str += "id:" +id + ""n";
str += "name:" + name + ""n";
if(person instanceof Student)
str += "major:" + ((Student) person).getStudentMajor() + ""n";
if(person instanceof Teacher)
str += "salary:" + ((Teacher) person).getTeacherSalary().toString() + ""n";
str += "dept:" + ""n";
str += " deptId:" + deptId + ""n";
str += " deptName:" + deptName + ""n";
str += " deptDesc:" + deptDesc + ""n";
str += ""n";
}
return str;
}
}
5、運行結(jié)果

【圖:separate_tables.jpg】
控制臺顯示:
......
Hibernate: select max(id) from mydepartment
Hibernate: select max(id) from thePerson
Hibernate: insert into db.mydepartment (name, descs, id) values (?, ?, ?)
Hibernate: insert into db.thePerson (name, dept, id) values (?, ?, ?)
Hibernate: insert into theStudent (studentMajor, id) values (?, ?)
Hibernate: insert into db.thePerson (name, dept, id) values (?, ?, ?)
Hibernate: insert into theTeacher (teacherSalary, id) values (?, ?)
Hibernate: select person0_.id as id0_, person0_.name as name0_, person0_.dept as dept0_, person0_1_.studentMajor as studentM2_1_, person0_2_.teacherSalary as teacherS2_2_, case when person0_1_.id is not null then 1 when person0_2_.id is not null then 2 when person0_.id is not null then 0 end as clazz_ from db.thePerson person0_ left outer join theStudent person0_1_ on person0_.id=person0_1_.id left outer join theTeacher person0_2_ on person0_.id=person0_2_.id
Hibernate: select department0_.id as id3_0_, department0_.name as name3_0_, department0_.descs as descs3_0_ from db.mydepartment department0_ where department0_.id=?
id:1
name:Sam
major:Math
dept:
deptId:1
deptName:college of math
deptDesc:the top 3 college
id:2
name:Martin
salary:15000.0
dept:
deptId:1
deptName:college of math
deptDesc:the top 3 college
[參考資料]:
《J2EE項目實訓(xùn)--Hibernate框架技術(shù)》-楊少波 : 清華大學(xué)出版社
原創(chuàng)作品,轉(zhuǎn)載請注明出處。
作者:Winty (wintys@gmail.com)
博客:http://m.tkk7.com/wintys
posted on 2009-06-21 13:31
天堂露珠 閱讀(1464)
評論(0) 編輯 收藏 所屬分類:
Hibernate