随笔 - 117  文章 - 72  trackbacks - 0

声明:原创作品(标有[原]字样)转载时请注明出处,谢谢。

常用链接

常用设置
常用软件
常用命令
 

订阅

订阅

留言簿(7)

随笔分类(130)

随笔档案(123)

搜索

  •  

积分与排名

  • 积分 - 154454
  • 排名 - 389

最新评论

[标题]:[原]Hibernate继承映射-继承关系中每个类均映射为一个数据库表
[时间]:2009-6-21
[摘要]:继承关系中每个类均映射为一个数据库表优点:此时,与面向对象的概念是一致的,这种映射实现策略的最大好处就是关系模型完全标准化,关系模型和领域模型完全一致,易于修改基类和增加新的子类。缺点:数据库中存在大量的表,为细粒度级的数据模型,访问数据时将存在大量的关联表的操作,效率较低。
[关键字]:Hibernate,ORM,关联,继承,持久化,映射,Abstract
[环境]:MyEclipse7,Hibernate3.2,MySQL5.1
[作者]:Winty (wintys@gmail.com) http://www.blogjava.net/wintys

[正文]:
    继承关系中每个类均映射为一个数据库表。
优点:
    此时,与面向对象的概念是一致的,这种映射实现策略的最大好处就是关系模型完全标准化,关系模型和领域模型完全一致,易于修改基类和增加新的子类。

缺点:
    数据库中存在大量的表,为细粒度级的数据模型,访问数据时将存在大量的关联表的操作,效率较低。

    
    例:学校管理系统中的实体关系:

    【图:department.jpg】
1、概述
a.实体类
    与allinone包中的实体类相同。

b.数据库表
    继承关系中每个类均映射为一个数据库表。

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、数据库表:

【图:separate_db.jpg】
db.sql:
-- Author:Winty (wintys@gmail.com)
-- Date:2009-06-20
-- http://www.blogjava.net/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关联
    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&amp;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);
            //多态保存
            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();
        //支持多态查询
        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、运行结果

【图: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项目实训--Hibernate框架技术》-杨少波 : 清华大学出版社
原创作品,转载请注明出处。
作者:Winty (wintys@gmail.com)
博客:http://www.blogjava.net/wintys

posted on 2009-06-21 13:31 天堂露珠 阅读(1458) 评论(0)  编辑  收藏 所属分类: Hibernate

只有注册用户登录后才能发表评论。


网站导航: