欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java的Hibernate框架中复合主键映射的创建和使用教程

程序员文章站 2024-03-13 11:06:03
复合主键映射需要在映射配置文件中使用标签,该标签是指将一个类指定为相应的复合主键,它的name属性需要指定类文件中定义的属性值,并在...

复合主键映射需要在映射配置文件中使用<composite-id>标签,该标签是指将一个类指定为相应的复合主键,它的name属性需要指定类文件中定义的属性值,并在该标签中添加<key-property>子标签。
note:想要使用复合映射必须要将复合主键放到一个类中,也就是讲复合主键属性和其它属性分到两个类中,并将复合主键的类实现接口serializable,该接口隶属于java.io。
复合主键的映射关系的主键是由多个列复合而成的,对应到数据表中相当的简单,如下图:

Java的Hibernate框架中复合主键映射的创建和使用教程

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)) 

对应的表结构如下图:

Java的Hibernate框架中复合主键映射的创建和使用教程

 

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 (?, ?, ?, ?, ?) 
相应的数据库视图:

Java的Hibernate框架中复合主键映射的创建和使用教程

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