複合主鍵(二)


可以將主鍵的資訊獨立為一個類別,例如:
  • UserPK.java
package onlyfun.caterpillar;

import java.io.Serializable;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

public class UserPK implements Serializable {
private String name;
private String phone;

public String getName() {
return name;
}

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

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public boolean equals(Object obj) {
if(obj == this) {
return true;
}

if(!(obj instanceof User)) {
return false;
}

UserPK pk = (UserPK) obj;
return new EqualsBuilder()
.append(this.name, pk.getName())
.append(this.phone, pk.getPhone())
.isEquals();
}

public int hashCode() {
return new HashCodeBuilder()
.append(this.name)
.append(this.phone)
.toHashCode();
}
}

現在User類別的主鍵資訊被分離出來了,例如:
  • User.java
package onlyfun.caterpillar;

import java.io.Serializable;

public class User implements Serializable {
private UserPK userPK; // 主鍵
private Integer age;

public User() {}

public UserPK getUserPK() {
return userPK;
}

public void setUserPK(UserPK userPK) {
this.userPK = userPK;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}

在映射文件方面,需要指定主鍵類的資訊,例如:
  • User.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">

<hibernate-mapping>

<class name="onlyfun.caterpillar.User" table="user">
<composite-id name="userPK"
class="onlyfun.caterpillar.UserPK"
unsaved-value="any">
<key-property name="name"
column="name"/>
<key-property name="phone"
column="phone"/>
</composite-id>

<property name="age" column="age"/>

</class>

</hibernate-mapping>

在查詢資料時,必須指定主鍵資訊,例如:
UserPK pk = new UserPK();
pk.setName("bush");
pk.setPhone("0970123456");
       
Session session = sessionFactory.openSession();
// 以主鍵類實例設定複合主鍵並載入對應的資料
User user = (User) session.load(User.class, pk);
       
System.out.println(user.getAge() + "\t" +
                                  user.getUserPK().getName() + "\t" +
                                  user.getUserPK().getPhone());
session.close();