复合主键也可以采用嵌入式主键替代,例如将上一小节中复合主键修改成嵌入式主键的步骤如下:
(1)编写一个嵌入式主键的类CustomerPK,代码如下。
import java.io.Serializable;
?
@Embeddable
public class CustomerPK implements Serializable {
?
???????? public CustomerPK() {}
?
???????? public CustomerPK(String name, String email) {
?????????????????? this.name = name;
?????????????????? this.email = email;
???????? }
/**其他代码与上一小节中相同*/
}
作为嵌入式主键类,要满足以下几点要求。
l???????? 必须实现Serializable接口、必须有默认的public无参数的构造方法、必须覆盖equals 和hashCode方法,这些要求与使用复合主键的要求相同。
l???????? 将嵌入式主键类使用@Embeddable标注,表示这个是一个嵌入式类。
(2)通过@EmbeddedId注释标注实体中的嵌入式主键,实体代码如下。
@Entity
@Table(name = "customer")
public class CustomerEO implements java.io.Serializable {
?
???????? public CustomerEO() {
???????? }
?
???????? public CustomerEO( String name, String email) {
?????????????????? this.id = new CustomerPK(name,email);
???????? }
?
???????? /** 嵌入式主键 */
@EmbeddedId
???????? private CustomerPK id ;
?
???????? private String name;
?
???????? /** 客户名称 */
???????? @Column(name = "name")
???????? public String getName() {
?????????????????? return this.id.getName();
???????? }
?
???????? public void setName(String name) {
?????????????????? this.id.setName(name) ;
???????? }
????????
???????? private String email;
????????
???????? @Column(name = "email")
???????? public String getEmail() {
?????????????????? return this.id.getEmail();
???????? }
?
???????? public void setEmail(String email) {
?????????????????? this.id.setEmail(email);
???????? }
?
}
(3)这样定义实体的嵌入式主键后,通过以下代码便可以获得指定的实体对象。
public CustomerEO findCustomer( String name ,String email){
???????? return (CustomerEO)
???????? entityManager.createQuery("SELECT c FROM CustomerEO c WHERE c.id.name = ?1 AND e.id.email = ?2")
???????? .setParameter(1, name)
???????? .setParameter(2, email)
???????? .getSingleResult();
}