復合主鍵映射需要在映射配置文件中使用<composite-id>標簽,該標簽是指將一個類指定為相應的復合主鍵,它的name屬性需要指定類文件中定義的屬性值,并在該標簽中添加<key-property>子標簽。
Note:想要使用復合映射必須要將復合主鍵放到一個類中,也就是講復合主鍵屬性和其它屬性分到兩個類中,并將復合主鍵的類實現接口Serializable,該接口隸屬于java.io。
復合主鍵的映射關系的主鍵是由多個列復合而成的,對應到數據表中相當的簡單,如下圖:
1、類文件
這里就拿上圖的表來作為示例,在表中有兩個字段年限和持續時間組合成為表的主鍵,所以分成的新類分別命名為FiscalYearPeriod和FiscalYearPeriodPK,其中FiscalYearPeriodPK類封裝表的主鍵屬性,FiscalYearPeriod類封裝其它屬性以及FiscalYearPeriodPK類。
1.1 FiscalYearPeriod.java
類中封裝有基本的屬性,并把FiscalYearPeriodPK類作為屬性封裝到類中,并在配置文件中配置相應的映射,如下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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>標簽中要指定該類,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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類添加映射即可,在該映射文件中添加對應復合主鍵標簽,并在標簽中添加對應的主鍵屬性,如下代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<? 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語句如下:
1
2
|
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 寫入操作
寫入的操作方法和以前的寫入方法相同,需要定義兩個對象,然后保存相應的對象信息到數據庫中,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
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 加載操作
相應的加載方法會和以前不同,因為在該表中主鍵是復合屬性,所以需要創建一個類。在加載數據時需要創建主鍵對象,此時的主鍵就是一個對象,更需要為對象的屬性賦值,這樣才能獲取對象,代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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); } } |
生成的結果,如下:
1
2
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<? 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<? 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
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); } } } |