有時一個實體的主鍵可能同時為多個
(
CustomerPK
import java
public class CustomerPK implements Serializable {
public CustomerPK() {
}
public CustomerPK(String name
this
this
}
private String email ;
public String getEmail () {
return email ;
}
public void setEmail (String email ) {
this
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this
}
@Override
public int hashCode() {
final int PRIME =
int result =
result = PRIME * result + ((email == null ) ?
result = PRIME * result + ((name == null ) ?
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null )
return false;
if (getClass() != obj
return false;
final CustomerPK other = (CustomerPK) obj;
if (email == null ) {
if (other
return false;
} else if (!email
return false;
if (name == null ) {
if (other
return false;
} else if (!name
return false;
return true;
}
}
作為符合主鍵類
l 必須實現Serializable接口
l 必須有默認的public無參數的構造方法
l 必須覆蓋equals和hashCode方法
(
@Entity
@Table(name =
@IdClass(CustomerPK
public class CustomerEO implements java
private Integer id;
public Integer getId() {
return this
}
public void setId(Integer id) {
this
}
private String name;
@Id
public String getName() {
return this
}
public void setName(String name) {
this
}
private String email ;
@Id
public String getEmail () {
return email ;
}
public void setEmail (String email ) {
this
}
}
標注復合主鍵時需要注意以下幾個問題
l @IdClass標注用於標注實體所使用主鍵規則的類
@Target({TYPE}) @Retention(RUNTIME)
public @interface IdClass {
Class value();
}
屬性Class表示符合主鍵所使用的類
l 在實體中同時標注主鍵的屬性
(
CustomerPK cpk = new CustomerPK(
CustomerEO instance = entityManager
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28128.html