<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    隨筆 - 117  文章 - 72  trackbacks - 0

    聲明:原創(chuàng)作品(標有[原]字樣)轉載時請注明出處,謝謝。

    常用鏈接

    常用設置
    常用軟件
    常用命令
     

    訂閱

    訂閱

    留言簿(7)

    隨筆分類(130)

    隨筆檔案(123)

    搜索

    •  

    積分與排名

    • 積分 - 155734
    • 排名 - 389

    最新評論

    [標題]:[原]Hibernate繼承映射-繼承關系中每個類均映射為一個數(shù)據庫表
    [時間]:2009-6-21
    [摘要]:繼承關系中每個類均映射為一個數(shù)據庫表優(yōu)點:此時,與面向對象的概念是一致的,這種映射實現(xiàn)策略的最大好處就是關系模型完全標準化,關系模型和領域模型完全一致,易于修改基類和增加新的子類。缺點:數(shù)據庫中存在大量的表,為細粒度級的數(shù)據模型,訪問數(shù)據時將存在大量的關聯(lián)表的操作,效率較低。
    [關鍵字]:Hibernate,ORM,關聯(lián),繼承,持久化,映射,Abstract
    [環(huán)境]:MyEclipse7,Hibernate3.2,MySQL5.1
    [作者]:Winty (wintys@gmail.com) http://m.tkk7.com/wintys

    [正文]:
        繼承關系中每個類均映射為一個數(shù)據庫表。
    優(yōu)點:
        此時,與面向對象的概念是一致的,這種映射實現(xiàn)策略的最大好處就是關系模型完全標準化,關系模型和領域模型完全一致,易于修改基類和增加新的子類。

    缺點:
        數(shù)據庫中存在大量的表,為細粒度級的數(shù)據模型,訪問數(shù)據時將存在大量的關聯(lián)表的操作,效率較低。

        
        例:學校管理系統(tǒng)中的實體關系:

        【圖:department.jpg】
    1、概述
    a.實體類
        與allinone包中的實體類相同。

    b.數(shù)據庫表
        繼承關系中每個類均映射為一個數(shù)據庫表。

    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ù)據庫表:

    【圖: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關聯(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&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);
                //多態(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、運行結果

    【圖: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框架技術》-楊少波 : 清華大學出版社
    原創(chuàng)作品,轉載請注明出處。
    作者:Winty (wintys@gmail.com)
    博客:http://m.tkk7.com/wintys

    posted on 2009-06-21 13:31 天堂露珠 閱讀(1464) 評論(0)  編輯  收藏 所屬分類: Hibernate
    主站蜘蛛池模板: 99视频免费播放| 中文字幕不卡高清免费| 很黄很污的网站免费| 成人亚洲网站www在线观看| 亚洲av日韩av永久无码电影| 大学生美女毛片免费视频| 亚洲人片在线观看天堂无码| 24小时日本在线www免费的| 亚洲国产成a人v在线观看| 青青视频观看免费99| 久久久久亚洲国产| 免费高清在线影片一区| 亚洲av无码专区青青草原| heyzo亚洲精品日韩| 久久高潮一级毛片免费| 亚洲AV无码专区国产乱码电影 | 免费大香伊蕉在人线国产| 国产精品亚洲а∨天堂2021| 亚洲国产精品不卡毛片a在线| 国产免费久久久久久无码| 亚洲AV永久无码精品| 中文字幕免费观看| 亚洲欧洲精品成人久久曰| 国产在线观看免费视频播放器| 免费无遮挡无码视频在线观看| 国产亚洲精品免费视频播放| 99视频在线精品免费| 亚洲依依成人亚洲社区| 亚洲AV无码成H人在线观看| 三年片在线观看免费| 亚洲国产福利精品一区二区| 在线观看免费精品国产| 久久成人永久免费播放| 亚洲国产片在线观看| 免费中文字幕一级毛片| 成全视频在线观看免费| 亚洲欧洲无码一区二区三区| 国产AV无码专区亚洲精品| 免费一本色道久久一区| 二区久久国产乱子伦免费精品| 亚洲日产2021三区|