<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)作品(標(biāo)有[原]字樣)轉(zhuǎn)載時(shí)請(qǐng)注明出處,謝謝。

    常用鏈接

    常用設(shè)置
    常用軟件
    常用命令
     

    訂閱

    訂閱

    留言簿(7)

    隨筆分類(130)

    隨筆檔案(123)

    搜索

    •  

    積分與排名

    • 積分 - 155667
    • 排名 - 391

    最新評(píng)論

    [標(biāo)題]:[原]Hibernate繼承映射-具體類映射為數(shù)據(jù)庫(kù)表
    [時(shí)間]:2009-6-21
    [摘要]:每一個(gè)具體子類映射成單個(gè)數(shù)據(jù)庫(kù)表,而抽象基類不參與映射。優(yōu)點(diǎn):數(shù)據(jù)操作實(shí)現(xiàn)簡(jiǎn)單,每個(gè)表中都包含自己所需要的具體子類的所有信息,減少了多表關(guān)聯(lián)操作時(shí)的性能消耗。缺點(diǎn):類的修改會(huì)導(dǎo)致相對(duì)應(yīng)的表及其子類所對(duì)應(yīng)表的更改。不支持多態(tài)查詢。應(yīng)用:適合在類層次結(jié)構(gòu)上有一定數(shù)量的抽象類的情況下使用。
    [關(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

    [正文]:
        每一個(gè)具體子類映射成單個(gè)數(shù)據(jù)庫(kù)表,而抽象基類不參與映射。
    優(yōu)點(diǎn):數(shù)據(jù)操作實(shí)現(xiàn)簡(jiǎn)單,每個(gè)表中都包含自己所需要的具體子類的所有信息,減少了多表關(guān)聯(lián)操作時(shí)的性能消耗。

    缺點(diǎn):
        類的修改會(huì)導(dǎo)致相對(duì)應(yīng)的表及其子類所對(duì)應(yīng)表的更改。不支持多態(tài)查詢。

    應(yīng)用:
        適合在類層次結(jié)構(gòu)上有一定數(shù)量的抽象類的情況下使用。
        
        例:學(xué)校管理系統(tǒng)中的實(shí)體關(guān)系:

        【圖:department.jpg】
    1、概述
    a.實(shí)體類
    public class Department {
        ......
        //由于Person類沒(méi)有被映射,所以無(wú)法實(shí)現(xiàn)Department到Person的關(guān)聯(lián)
        ......
    }

    public abstract class Person {
        ......
        private Department department;
        ......
    }

    public class Student extends Person {
        ......
    }

    public class Teacher extends Person {
        ......
    }

    b.數(shù)據(jù)庫(kù)表
        具體子類Student和Teacher分別映射成一張表,各自的表中都包含從父類繼承來(lái)的屬性。

    c.配置文件
    由于Person類沒(méi)有被映射,所以無(wú)法映射Person到Department的關(guān)聯(lián),只能由子類Student和Teacher實(shí)現(xiàn)映射。

    Student.hbm.xml:
    包含父類屬性的映射
    ......
    <many-to-one name="department"
                unique="true"
                column="dept"
                class="wintys.hibernate.inheritance.concrete.Department"/>
    ......


    Teacher.hbm.xml:
    包含父類屬性的映射
    ......
    <many-to-one name="department"
                unique="true"
                column="dept"
                class="wintys.hibernate.inheritance.concrete.Department"/>
    ......

    2、實(shí)體類:
    Department.java:
    package wintys.hibernate.inheritance.concrete;

    /**
     *
     * @version 2009-06-20
     * @author Winty (wintys@gmail.com)
     *
     */
    public class Department {
        private Integer id;
        private String name;
        private String desc;
        
        
        public Department(){
            
        }
        
        public Department(String name , String desc){
            this.name = name;
            this.desc = desc;
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getDesc() {
            return desc;
        }
        public void setDesc(String desc) {
            this.desc = desc;
        }
    }


    Person.java:
    package wintys.hibernate.inheritance.concrete;

    /**
     *
     * @version 2009-06-20
     * @author Winty (wintys@gmail.com)
     *
     */
    public abstract class Person {
        private Integer id;
        private String name;
        private Department department;
        
        public Person(){
        }
        
        public Person(String name){
            this.name = name;
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Department getDepartment() {
            return department;
        }
        public void setDepartment(Department department) {
            this.department = department;
        }
    }


    Student.java:
    package wintys.hibernate.inheritance.concrete;

    /**
     *
     * @version 2009-06-20
     * @author Winty (wintys@gmail.com)
     *
     */
    public class Student extends Person {
        private String studentMajor;
        
        public Student(){
            
        }
        
        public Student(String name , String major){
            super(name);
            this.studentMajor = major;
        }

        public String getStudentMajor() {
            return studentMajor;
        }

        public void setStudentMajor(String studentMajor) {
            this.studentMajor = studentMajor;
        }
    }


    Teacher.java:
    package wintys.hibernate.inheritance.concrete;

    /**
     *
     * @version 2009-06-20
     * @author Winty (wintys@gmail.com)
     *
     */
    public class Teacher extends Person {
        private Float teacherSalary;

        public Teacher(){
            
        }
        
        public Teacher(String name , Float teacherSalary){
            super(name);
            this.teacherSalary = teacherSalary;
        }
        
        public Float getTeacherSalary() {
            return teacherSalary;
        }

        public void setTeacherSalary(Float teacherSalary) {
            this.teacherSalary = teacherSalary;
        }
    }



    3、數(shù)據(jù)庫(kù)表:

    【圖:concret_db.jpg】
    db.sql:
    -- Author:Winty (wintys@gmail.com)
    -- Date:2009-06-20
    -- http://m.tkk7.com/wintys

    -- Department
    CREATE TABLE mydepartment(
        id      INT(4) NOT NULL,
        name    VARCHAR(100),
        descs  VARCHAR(100),
        PRIMARY KEY(id)
    );

    -- Student
    CREATE TABLE mystudent(
        id              INT(4) NOT NULL,
        name            VARCHAR(100),
        dept            INT(4),-- 從Person繼承了與Department的關(guān)聯(lián)
        studentMajor    VARCHAR(100),
        PRIMARY KEY(id),
        CONSTRAINT FK_dept_s FOREIGN KEY(dept) REFERENCES mydepartment(id)
    );

    -- Teacher
    CREATE TABLE myteacher(
        id              INT(4) NOT NULL,
        name            VARCHAR(100),
        dept            INT(4), -- 從Person繼承了與Department的關(guān)聯(lián)
        teacherSalary   FLOAT(7,2),
        PRIMARY KEY(id),
        CONSTRAINT FK_dept_t FOREIGN KEY(dept) REFERENCES mydepartment(id)
    );

    4、映射文件:

    【圖:concrete_mapping.jpg】
    Department.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.concrete.Department" table="mydepartment" catalog="db">
            <id name="id" type="int">
                <column name="id" not-null="true"/>
                <generator class="increment" />
            </id>
            <property name="name" />
            <property name="desc" type="string" column="descs"/>
        </class>
    </hibernate-mapping>


    Student.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.concrete.Student" table="mystudent" catalog="db">
            <id name="id" type="int">
                <column name="id" not-null="true"/>
                <generator class="increment" />
            </id>
            <property name="name" />
            <property name="studentMajor" />
            
            <many-to-one name="department"
                        unique="true"
                        column="dept"
                        class="wintys.hibernate.inheritance.concrete.Department"/>
        </class>
    </hibernate-mapping>


    Teacher.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.concrete.Teacher" table="myteacher" catalog="db">
            <id name="id" type="int">
                <column name="id" not-null="true"/>
                <generator class="increment" />
            </id>
            <property name="name" />
            <property name="teacherSalary" type="float"/>
            
            <many-to-one name="department"
                        unique="true"
                        column="dept"
                        class="wintys.hibernate.inheritance.concrete.Department"/>
        </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/concrete/Department.hbm.xml" />
        <mapping
            resource="wintys/hibernate/inheritance/concrete/Student.hbm.xml" />
        <mapping
            resource="wintys/hibernate/inheritance/concrete/Teacher.hbm.xml" />

    </session-factory>

    </hibernate-configuration>


    4、使用測(cè)試:
    DAO.java:
    package wintys.hibernate.inheritance.concrete;

    import java.util.List;

    public interface DAO {
        public void insert();
        public <T> List<T> select(String hql);
    }


    DAOBean.java:
    package wintys.hibernate.inheritance.concrete;

    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;
        }
    }


    HibernateUtil.java:
    package wintys.hibernate.inheritance.concrete;

    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;

    /**
     * Hibernate Session管理
     * @author Winty
     */
    public class HibernateUtil {
        private static SessionFactory factory = null;
        private static ThreadLocal<Session> threadLocal;
            
        static {    
            threadLocal = new ThreadLocal<Session>();
        }
        
        private HibernateUtil(){    
        }
        
        //Should be call only once.
        //設(shè)置Hibernate.cfg.xml的位置
        public static void setConfigFile(String hibernate_cfg_xml){
            try{
                factory = new Configuration()
                        .configure(hibernate_cfg_xml)
                        .buildSessionFactory();
            }catch(HibernateException e){
                System.err.println(e.getMessage());
            }
        }
        
        public static Session getSession()throws HibernateException{
            Session session = threadLocal.get();
            if(session == null){
                session = factory.openSession();
                threadLocal.set(session);
            }
            
            return session;
        }
        
        public static void closeSession()throws HibernateException{
            Session session = threadLocal.get();
            if(session != null){
                session.close();
            }
            threadLocal.set(null);
        }
    }



    Test.java:
    package wintys.hibernate.inheritance.concrete;

    import java.util.Iterator;
    import java.util.List;

    public class Test {

        public static void main(String[] args) {
            String config = "wintys/hibernate/inheritance/concrete/hibernate.cfg.xml";
            HibernateUtil.setConfigFile(config);
            
            DAO dao = new DAOBean();
            dao.insert();
            //不支持多態(tài)查詢
            //Error:Person is not mapped
            //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、運(yùn)行結(jié)果
    控制臺(tái)顯示:
    ......
    Hibernate: select max(id) from mydepartment
    Hibernate: select max(id) from mystudent
    Hibernate: select max(id) from myteacher
    Hibernate: insert into db.mydepartment (name, descs, id) values (?, ?, ?)
    Hibernate: insert into db.mystudent (name, studentMajor, dept, id) values (?, ?, ?, ?)
    Hibernate: insert into db.myteacher (name, teacherSalary, dept, id) values (?, ?, ?, ?)
    Hibernate: select student0_.id as id1_, student0_.name as name1_, student0_.studentMajor as studentM3_1_, student0_.dept as dept1_ from db.mystudent student0_
    Hibernate: select department0_.id as id0_0_, department0_.name as name0_0_, department0_.descs as descs0_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


    Hibernate: select teacher0_.id as id2_, teacher0_.name as name2_, teacher0_.teacherSalary as teacherS3_2_, teacher0_.dept as dept2_ from db.myteacher teacher0_
    id:1
    name:Martin
    salary:15000.0
    dept:
      deptId:1
      deptName:college of math
      deptDesc:the top 3 college

    [參考資料]:
    《J2EE項(xiàng)目實(shí)訓(xùn)--Hibernate框架技術(shù)》-楊少波 : 清華大學(xué)出版社
    原創(chuàng)作品,轉(zhuǎn)載請(qǐng)注明出處。
    作者:Winty (wintys@gmail.com)
    博客:http://m.tkk7.com/wintys

    posted on 2009-06-21 13:05 天堂露珠 閱讀(708) 評(píng)論(0)  編輯  收藏 所屬分類: Hibernate
    主站蜘蛛池模板: 国产免费不卡视频| 亚洲伊人色一综合网| 精品无码国产污污污免费| 欧洲人成在线免费| 性生大片视频免费观看一级| 在线综合亚洲欧洲综合网站| 亚洲视频在线播放| 亚洲精品蜜桃久久久久久| 国产乱弄免费视频| 成人毛片免费观看视频在线| **aaaaa毛片免费| 亚欧免费一级毛片| 免费国产成人α片| 大地资源中文在线观看免费版| 免费国产在线精品一区| 成人亚洲国产精品久久| 亚洲人成色在线观看| 亚洲六月丁香婷婷综合| 色播亚洲视频在线观看| 亚洲第一AV网站| 亚洲人成亚洲人成在线观看| 亚洲熟伦熟女新五十路熟妇 | 亚洲午夜久久久久妓女影院| 亚洲国产一区明星换脸| 亚洲精品美女久久久久99小说| 亚洲国产成人精品无码久久久久久综合| 好大好硬好爽免费视频| 国产精品成人免费一区二区 | 亚洲免费综合色在线视频| 亚洲中文字幕无码久久| 中文字幕乱码亚洲无线三区| 亚洲人xxx日本人18| 亚洲色欲色欱wwW在线| 亚洲精品无码人妻无码| 亚洲AV成人片无码网站| 色九月亚洲综合网| 免费又黄又爽又猛大片午夜| 中文字幕在线免费视频| 成人A片产无码免费视频在线观看| 暖暖日本免费中文字幕| 中文字幕亚洲免费无线观看日本 |