复合主键@idclass -凯发k8官方网
有时一个实体的主键可能同时为多个,例如同样是之前使用的“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;
}
}
作为符合主键类,要满足以下几点要求。
l 必须实现serializable接口。
l 必须有默认的public无参数的构造方法。
l 必须覆盖equals和hashcode方法。equals方法用于判断两个对象是否相同,entitymanger通过find方法来查找entity时,是根据equals的返回值来判断的。本例中,只有对象的name和email值完全相同时或同一个对象时则返回true,否则返回false。hashcode方法返回当前对象的哈希码,生成的hashcode相同的概率越小越好,算法可以进行优化。
(2)通过@idclass注释在实体中标注复合主键,实体代码如下。
@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;
}
}
标注复合主键时需要注意以下几个问题。
l @idclass标注用于标注实体所使用主键规则的类。它的定义如下所示。
@target({type}) @retention(runtime)
public @interface idclass {
class value();
}
属性class表示符合主键所使用的类,本例中使用customerpk这个复合主键类。
l 在实体中同时标注主键的属性。本例中在email和name的getter方法前标注@id,表示符合主键使用这两个属性。
(3)这样定义实体的复合主键后,通过以下代码便可以获得指定的实体对象:
customerpk cpk = new customerpk("janet","janetvsfei@yahoo.com.cn");
customereo instance = entitymanager.find(customereo.class, cpk);
总结
以上是凯发k8官方网为你收集整理的复合主键@idclass的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇:
- 下一篇: