hibernate注解方式實現(xiàn)復(fù)合主鍵
有時一個實體的主鍵可能同時為多個,例如同樣是之前使用的“CustomerEO”實體,需要通過name和email來查找指定實體,當(dāng)且僅當(dāng)name和email的值完全相同時,才認(rèn)為是相同的實體對象。要配置這樣的復(fù)合主鍵,步驟如以下所示。
(1)編寫一個復(fù)合主鍵的類CustomerPK,代碼如下。
CustomerPK.java
import java.io.Serializable;
public class CustomerPK implements Serializable {
public CustomerPK() {
}
public CustomerPK(String name, String email) {
this.name = name;
this.email = email;
}
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((email == null) ? 0 : email.hashCode());
result = PRIME * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final CustomerPK other = (CustomerPK) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
作為符合主鍵類,要滿足以下幾點要求。
l 必須實現(xiàn)Serializable接口。
l 必須有默認(rèn)的public無參數(shù)的構(gòu)造方法。
l 必須覆蓋equals和hashCode方法。equals方法用于判斷兩個對象是否相同,EntityManger通過find方法來查找Entity時,是根據(jù)equals的返回值來判斷的。本例中,只有對象的name和email值完全相同時或同一個對象時則返回true,否則返回false。hashCode方法返回當(dāng)前對象的哈希碼,生成的hashCode相同的概率越小越好,算法可以進行優(yōu)化。
(2)通過@IdClass注釋在實體中標(biāo)注復(fù)合主鍵,實體代碼如下。
@Entity
@Table(name = "customer")
@IdClass(CustomerPK.class)
public class CustomerEO implements java.io.Serializable {
private Integer id;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
private String name;
@Id
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
private String email;
@Id
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
標(biāo)注復(fù)合主鍵時需要注意以下幾個問題。
l @IdClass標(biāo)注用于標(biāo)注實體所使用主鍵規(guī)則的類。它的定義如下所示。
@Target({TYPE}) @Retention(RUNTIME)
public @interface IdClass {
Class value();
}
屬性Class表示符合主鍵所使用的類,本例中使用CustomerPK這個復(fù)合主鍵類。
l 在實體中同時標(biāo)注主鍵的屬性。本例中在email和name的getter方法前標(biāo)注@Id,表示符合主鍵使用這兩個屬性。
(3)這樣定義實體的復(fù)合主鍵后,通過以下代碼便可以獲得指定的實體對象:
CustomerPK cpk = new CustomerPK("Janet","janetvsfei@yahoo.com.cn");
CustomerEO instance = entityManager.find(CustomerEO.class, cpk);
本文來自CSDN博客,轉(zhuǎn)載請標(biāo)明出處:http://blog.csdn.net/EJB_JPA/archive/2008/05/09/2422540.aspx
posted on 2009-09-18 16:29 輕松 閱讀(10370) 評論(1) 編輯 收藏 所屬分類: Hibernate