Welcome 微信登录

首页 / 软件开发 / JAVA / hibernate注解方式实现复合主键

hibernate注解方式实现复合主键2011-01-08 BlogJava 轻松有时一个实体的主键可能同时为多个,例如同样是之前使用的“CustomerEO”实体,需要通过name和email来查找指定实体,当且仅当name和email的值完全相同时,才认为是相同的实体对象。要配置这样的复合主键,步骤如以下所示。

(1)编写一个复合主键的类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;
}

}