程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java的Hibernate框架中復合主鍵映照的創立和應用教程

Java的Hibernate框架中復合主鍵映照的創立和應用教程

編輯:關於JAVA

Java的Hibernate框架中復合主鍵映照的創立和應用教程。本站提示廣大學習愛好者:(Java的Hibernate框架中復合主鍵映照的創立和應用教程)文章只能為提供參考,不一定能成為您想要的結果。以下是Java的Hibernate框架中復合主鍵映照的創立和應用教程正文


復合主鍵映照須要在映照設置裝備擺設文件中應用<composite-id>標簽,該標簽是指將一個類指定為響應的復合主鍵,它的name屬性須要指定類文件中界說的屬性值,並在該標簽中添加<key-property>子標簽。
Note:想要應用復合映照必需要將復合主鍵放到一個類中,也就是講復合主鍵屬性和其它屬性分到兩個類中,並將復合主鍵的類完成接口Serializable,該接口附屬於java.io。
復合主鍵的映照關系的主鍵是由多個列復合而成的,對應到數據表中相當的簡略,以下圖:

1、類文件
這裡就拿上圖的表來作為示例,在表中有兩個字段年限和連續時光組分解為表的主鍵,所以分紅的新類分離定名為FiscalYearPeriod和FiscalYearPeriodPK,個中FiscalYearPeriodPK類封裝表的主鍵屬性,FiscalYearPeriod類封裝其它屬性和FiscalYearPeriodPK類。
1.1 FiscalYearPeriod.java
類中封裝有根本的屬性,並把FiscalYearPeriodPK類作為屬性封裝到類中,並在設置裝備擺設文件中設置裝備擺設響應的映照,以下代碼:

package com.src.hibernate; 
 
import java.sql.Date; 
 
public class FiscalYearPeriod { 
   
  //時光主鍵 
  private FiscalYearPeriodPK fiscalYearPeriodPK; 
  public FiscalYearPeriodPK getFiscalYearPeriodPK() { 
    return fiscalYearPeriodPK; 
  } 
  public void setFiscalYearPeriodPK(FiscalYearPeriodPK fiscalYearPeriodPK) { 
    this.fiscalYearPeriodPK = fiscalYearPeriodPK; 
  } 
   
  //開端日期 
  private Date beginDate; 
  public Date getBeginDate() { 
    return beginDate; 
  } 
  public void setBeginDate(Date beginDate) { 
    this.beginDate = beginDate; 
  } 
   
  //停止日期 
  private Date endDate; 
  public Date getEndDate() { 
    return endDate; 
  } 
  public void setEndDate(Date endDate) { 
    this.endDate = endDate; 
  } 
   
  //階段時光 
  private String periodSts; 
  public String getPeriodSts() { 
    return periodSts; 
  } 
  public void setPeriodSts(String periodSts) { 
    this.periodSts = periodSts; 
  } 
} 

1.2 FiscalYearPeriodPK.java
封裝主鍵屬性,該類是從FiscalYearPeriod類平分離出來的,包括了根本的主鍵屬性,而且須要完成接口Serializable,該類是要映照到設置裝備擺設文件中<composite-id>標簽中要指定該類,代碼以下:

package com.src.hibernate; 
 
import java.io.Serializable; 
 
public class FiscalYearPeriodPK implements Serializable { 
   
  //年限 
  private int fiscalYear; 
  public int getFiscalYear() { 
    return fiscalYear; 
  } 
  public void setFiscalYear(int fiscalYear) { 
    this.fiscalYear = fiscalYear; 
  } 
 
  //連續時光 
  private int fiscalPeriod; 
  public int getFiscalPeriod() { 
    return fiscalPeriod; 
  } 
 
  public void setFiscalPeriod(int fiscalPeriod) { 
    this.fiscalPeriod = fiscalPeriod; 
  } 
   
} 

 

2、設置裝備擺設文件
這裡有個疑問兩個類都是哪一個須要添加映照文件?由於會應用<composite-id>標簽,所以只須要為FiscalYearPeriod類添加映照便可,在該映照文件中添加對應復合主鍵標簽,並在標簽中添加對應的主鍵屬性,以下代碼:

<?xml version="1.0"?> 
<!DOCTYPE hibernate-mapping PUBLIC  
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
  <class name="com.src.hibernate.FiscalYearPeriod" table="t_fiscal_year_period_pk"> 
    <composite-id name="fiscalYearPeriodPK"> 
      <key-property name="fiscalYear"></key-property> 
      <key-property name="fiscalPeriod"></key-property> 
    </composite-id> 
    <property name="beginDate" type="date"/> 
    <property name="endDate" type="date"/> 
    <property name="periodSts"/> 
  </class> 
</hibernate-mapping> 

將下面的文件生成對應的數據庫表,生成的sql語句以下:

drop table if exists t_fiscal_year_period_pk 
create table t_fiscal_year_period_pk (fiscalYear integer not null, fiscalPeriod integer not null, beginDate date, endDate date, periodSts varchar(255), primary key (fiscalYear, fiscalPeriod)) 

對應的表構造以下圖:

 

3、數據操作
響應的映照文件設置裝備擺設好後,響應的數據操作就變得很簡略了,起首從寫入數據開端,向數據庫中寫入數據時會同時把兩個類寫入到數據庫中,所以此時這兩個類都必需轉化為Transient狀況,所以在保留時須要起首將FiscalYearPeriod對象起首保留到數據庫中,然後它會主動聯系關系復合屬性,將信息保留到數據庫中。
3.1 寫入操作
寫入的操作辦法和之前的寫入辦法雷同,須要界說兩個對象,然後保留響應的對象信息到數據庫中,代碼以下:

public void testSave1(){ 
  //聲明會話對象 
  Session session=null; 
   
  try{ 
    //獲得會話對象 
    session=HibernateUtils.getSession(); 
    //開啟會話 
    session.beginTransaction(); 
    //創立復合對象 
    FiscalYearPeriodPK fiscalyearperiodpk=new FiscalYearPeriodPK(); 
    fiscalyearperiodpk.setFiscalPeriod(2014); 
    fiscalyearperiodpk.setFiscalYear(2012); 
     
    //創立對象 
    FiscalYearPeriod fiscalyearperiod=new FiscalYearPeriod(); 
    fiscalyearperiod.setFiscalYearPeriodPK(fiscalyearperiodpk); 
     
    session.save(fiscalyearperiod); 
    //提交會話 
    session.getTransaction().commit(); 
  }catch(Exception e){ 
    e.printStackTrace(); 
    session.getTransaction().rollback(); 
  }finally{ 
    HibernateUtils.closeSession(session); 
  } 
} 

履行響應的測試辦法,生成的SQL語句以下:

Hibernate: insert into t_fiscal_year_period_pk (beginDate, endDate, periodSts, fiscalYear, fiscalPeriod) values (?, ?, ?, ?, ?) 
響應的數據庫視圖:

3.2 加載操作
響應的加載辦法會和之前分歧,由於在該表中主鍵是復合屬性,所以須要創立一個類。在加載數據時須要創立主鍵對象,此時的主鍵就是一個對象,更須要為對象的屬性賦值,如許能力獲得對象,代碼以下:

public void testLoad1(){ 
  //聲明會話對象 
  Session session=null; 
   
  try{ 
    //獲得會話對象 
    session=HibernateUtils.getSession(); 
    //開啟會話 
    session.beginTransaction(); 
    //創立復合對象 
    FiscalYearPeriodPK fiscalyearperiodpk=new FiscalYearPeriodPK(); 
    fiscalyearperiodpk.setFiscalPeriod(2014); 
    fiscalyearperiodpk.setFiscalYear(2012); 
     
    FiscalYearPeriod fiscalyearperiod=(FiscalYearPeriod)session.load(FiscalYearPeriod.class,fiscalyearperiodpk); 
    System.out.println("開端日期: "+fiscalyearperiod.getBeginDate());  
    //提交會話 
    session.getTransaction().commit(); 
  }catch(Exception e){ 
    e.printStackTrace(); 
    session.getTransaction().rollback(); 
  }finally{ 
    HibernateUtils.closeSession(session); 
  } 
} 

生成的成果,以下:

Hibernate: select fiscalyear0_.fiscalYear as fiscalYear0_0_, fiscalyear0_.fiscalPeriod as fiscalPe2_0_0_, fiscalyear0_.beginDate as beginDate0_0_, fiscalyear0_.endDate as endDate0_0_, fiscalyear0_.periodSts as periodSts0_0_ from t_fiscal_year_period_pk fiscalyear0_ where fiscalyear0_.fiscalYear=? and fiscalyear0_.fiscalPeriod=? 
開端日期: 2013-10-12 

 

4、綜合示例
一個范圍較年夜公司的部分表(hibernate_dept_compositePK),由地點區域(area),部分名(name),本部分人數(empCount),組建時光(birthday)等字段構成,我們應用地點區域和部分名做結合主鍵:
4.1 目的類:Department.java

public class Department { 
 /** 把主鍵聯系關系屬性籠統出來零丁寫成一個類 */ 
 //private String area; 
 //private String name; 
 /**把主鍵類對象作為成員變量*/ 
 private DepartmentPK departmentPK; 
 private int empCount; 
 private Date birthday; 

// public String getArea() { 
//  return area; 
// } 
// 
// public void setArea(String area) { 
//  this.area = area; 
// } 
// 
// public String getName() { 
//  return name; 
// } 
// 
// public void setName(String name) { 
//  this.name = name; 
// } 
  
 public int getEmpCount() { 
  return empCount; 
 } 

 public void setEmpCount(int empCount) { 
  this.empCount = empCount; 
 } 

 public Date getBirthday() { 
  return birthday; 
 } 

 public void setBirthday(Date birthday) { 
  this.birthday = birthday; 
 } 

 public DepartmentPK getDepartmentPK() { 
  return departmentPK; 
 } 

 public void setDepartmentPK(DepartmentPK departmentPK) { 
  this.departmentPK = departmentPK; 
 } 

}

4.2主鍵類:DepartmentPK.java

public class DepartmentPK implements Serializable { 

 private static final long serialVersionUID = -288002855915204255L; 
 private String area; 
 private String name; 
 /** 
  * 籠罩hashCode辦法(依據area和name斷定) 
  */ 
 //@Override 
 public int hashCode() { 
  final int prime = 31; 
  int result = 1; 
  result = prime * result + ((area == null) ? 0 : area.hashCode()); 
  result = prime * result + ((name == null) ? 0 : name.hashCode()); 
  return result; 
 } 
 /** 
  * 籠罩equals(依據area和name斷定) 
  */ 
 @Override 
 public boolean equals(Object obj) { 
  if (this == obj) 
   return true; 
  if (obj == null) 
   return false; 
  if (getClass() != obj.getClass()) 
   return false; 
  final DepartmentPK other = (DepartmentPK) obj; 
  if (area == null) { 
   if (other.area != null) 
    return false; 
  } else if (!area.equals(other.area)) 
   return false; 
  if (name == null) { 
   if (other.name != null) 
    return false; 
  } else if (!name.equals(other.name)) 
   return false; 
  return true; 
 } 

 public String getArea() { 
  return area; 
 } 

 public void setArea(String area) { 
  this.area = area; 
 } 

 public String getName() { 
  return name; 
 } 

 public void setName(String name) { 
  this.name = name; 
 } 
}

4.3 映照文件Department.hbm.xml

<?xml version="1.0"?> 
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
 <class name="com.yangfei.hibernate.compositePk.entity.Department" table="hibernate_dept_compositePK"> 
  <!-- 結合主鍵 --> 
  <!-- name指的是主鍵對象屬性 --> 
  <composite-id name="departmentPK"> 
   <!-- 這裡是主鍵聯系關系屬性 --> 
   <key-property name="area" /> 
   <key-property name="name" /> 
  </composite-id> 
  <!-- 其它屬性 --> 
  <property name="empCount" length="4" /> 
  <property name="birthday" type="date" /> 
 </class> 
</hibernate-mapping>

4.4 hibernate設置裝備擺設文件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="dialect">org.hibernate.dialect.Oracle9Dialect</property> 
        <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl10</property> 
        <property name="connection.username">scott</property> 
        <property name="connection.password">yf123</property> 
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> 
        <property name="hibernate.show_sql">true</property> 
      
     <mapping resource="com/yangfei/hibernate/compositePk/entity/Department.hbm.xml"/> 
    </session-factory> 
</hibernate-configuration>

4.5測試類:DepartmentTest.java

public class DepartmentTest extends TestCase { 
 /** 
  * 測試拔出數據 
  */ 
 public void save() { 
  Session session = HibernateUtils.getSession(); 
  Transaction t = session.beginTransaction(); 
  try { 
   Department dept = new Department(); 
   /** 生成主鍵對象 */ 
   DepartmentPK deptPK = new DepartmentPK(); 
   deptPK.setArea("北京"); 
   deptPK.setName("研發部"); 
   dept.setDepartmentPK(deptPK); 

   dept.setEmpCount(100); 
   dept.setBirthday(new Date()); 

   session.save(dept); 
   t.commit(); 
  } catch (HibernateException e) { 
   e.printStackTrace(); 
   t.rollback(); 
  } finally { 
   HibernateUtils.closeSession(session); 
  } 
 } 
 /** 
  * 測試加載數據 
  */ 
 public void load() { 
  Session session = HibernateUtils.getSession(); 
  Transaction t = session.beginTransaction(); 
  try { 
   /** 生成主鍵對象 */ 
   DepartmentPK deptPK = new DepartmentPK(); 
   deptPK.setArea("北京"); 
   deptPK.setName("研發部"); 

   Department dept=(Department)session.load(Department.class, deptPK); 
   System.out.println(dept.getDepartmentPK().getArea()+","+dept.getDepartmentPK().getName()+","+dept.getEmpCount()+","+dept.getBirthday()); 
  } catch (HibernateException e) { 
   e.printStackTrace(); 
   t.rollback(); 
  } finally { 
   HibernateUtils.closeSession(session); 
  } 
 } 
  
 /** 
  * 測試修正數據 
  */ 
 public void update() { 
  Session session = HibernateUtils.getSession(); 
  Transaction t = session.beginTransaction(); 
  try { 
   /** 生成主鍵對象 */ 
   DepartmentPK deptPK = new DepartmentPK(); 
   deptPK.setArea("北京"); 
   deptPK.setName("研發部"); 

   Department emp=(Department)session.load(Department.class, deptPK); 
   System.out.println(emp.getDepartmentPK().getArea()+","+emp.getDepartmentPK().getName()+","+emp.getEmpCount()+","+emp.getBirthday()); 
   emp.setEmpCount(100); 
   session.saveOrUpdate(emp); 
    
   /** 生成主鍵對象 */ 
   DepartmentPK deptPK2 = new DepartmentPK(); 
   deptPK2.setArea("北京"); 
   deptPK2.setName("研發部"); 
   Department dept=(Department)session.load(Department.class, deptPK2); 
   System.out.println(dept.getDepartmentPK().getArea()+","+dept.getDepartmentPK().getName()+","+dept.getEmpCount()+","+dept.getBirthday()); 
   t.commit(); 
  } catch (HibernateException e) { 
   e.printStackTrace(); 
   t.rollback(); 
  } finally { 
   HibernateUtils.closeSession(session); 
  } 
 } 
  
 /** 
  * 測試刪除數據 
  */ 
 public void delete() { 
  Session session = HibernateUtils.getSession(); 
  Transaction t = session.beginTransaction(); 
  try { 
   /** 生成主鍵對象 */ 
   DepartmentPK deptPK = new DepartmentPK(); 
   deptPK.setArea("北京"); 
   deptPK.setName("研發部"); 
    
   Department dept=(Department)session.load(Department.class, deptPK); 
   session.delete(dept); 
   t.commit(); 
  } catch (HibernateException e) { 
   e.printStackTrace(); 
   t.rollback(); 
  } finally { 
   HibernateUtils.closeSession(session); 
  } 
 } 
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved