隨筆 - 117  文章 - 72  trackbacks - 0

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

          常用鏈接

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

          訂閱

          訂閱

          留言簿(7)

          隨筆分類(130)

          隨筆檔案(123)

          搜索

          •  

          積分與排名

          • 積分 - 155531
          • 排名 - 390

          最新評論

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

          posted on 2009-06-21 13:31 天堂露珠 閱讀(1463) 評論(0)  編輯  收藏 所屬分類: Hibernate
          主站蜘蛛池模板: 隆化县| 根河市| 赞皇县| 灵武市| 烟台市| 阆中市| 土默特右旗| 沂源县| 樟树市| 台北市| 弥渡县| 武城县| 河间市| 甘洛县| 莱州市| 交口县| 郴州市| 观塘区| 盱眙县| 资阳市| 定州市| 博兴县| 阿坝县| 昌都县| 庆安县| 高唐县| 鄱阳县| 梓潼县| 三亚市| 兴义市| 新兴县| 乐业县| 林州市| 河源市| 津市市| 苏尼特右旗| 平江县| 阿巴嘎旗| 海原县| 公安县| 安达市|