
JPA (Java Persistence API) 中的 @IdClass(paymentIdClass) 注解用于定义Payment实体的复合主键。复合主键由多个字段组成,而非单个字段。
@IdClass的用途
@IdClass 指定 Payment 实体的主键由多个属性构成。 我们定义多个字段作为主键,而不是单个主键列。当实体没有单个自然唯一标识符,而是依赖多个字段的组合来唯一标识时,这非常必要。例如,Payment 实体可能拥有一个复合主键,包含:
-
customer: 指向Customer实体的外键 (整数) -
checkNumber: 表示支票号码的字符串
customer 和 checkNumber 的组合唯一标识每笔付款记录。
@IdClass的工作原理
@IdClass(PaymentId.class) 告诉 JPA,Payment 实体将使用 PaymentId 类作为其复合主键。
PaymentId 类必须:
- 是一个 JavaBean (拥有无参构造函数和 getter/setter 方法)。
- 实现
Serializable接口。 - 覆盖
equals()和hashCode()方法以确保正确的实体比较。 - 拥有与
Payment实体主键字段匹配的字段。
PaymentId类的结构
PaymentId 类应该如下构建:
import java.io.Serializable;
import java.util.Objects;
public class PaymentId implements Serializable {
private Integer customer; // 必须与 payment.customer 的类型匹配 (customer 的 ID)
private String checkNumber;
// 无参构造函数 (序列化必需)
public PaymentId() {}
public PaymentId(Integer customer, String checkNumber) {
this.customer = customer;
this.checkNumber = checkNumber;
}
// getter 和 setter 方法
public Integer getCustomer() { return customer; }
public void setCustomer(Integer customer) { this.customer = customer; }
public String getCheckNumber() { return checkNumber; }
public void setCheckNumber(String checkNumber) { this.checkNumber = checkNumber; }
// 覆盖 equals() 和 hashCode() 方法,用于 JPA 中的正确比较
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PaymentId that = (PaymentId) o;
return Objects.equals(customer, that.customer) && Objects.equals(checkNumber, that.checkNumber);
}
@Override
public int hashCode() {
return Objects.hash(customer, checkNumber);
}
}
- JPA 如何使用
@IdClass
持久化 Payment 实体时,JPA 使用 PaymentId 类来表示其主键。JPA 会检查数据库中是否存在具有相同复合主键的实体。
检索 Payment 实体时,JPA 使用 PaymentId 中定义的字段来重建复合主键。
- 替代方法:使用
@EmbeddedId
除了 @IdClass,另一种定义复合主键的方法是 @EmbeddedId,它直接将主键字段嵌入实体内部:
@Embeddable
public class PaymentId implements Serializable {
@ManyToOne
@JoinColumn(name = "customerNumber")
private Customer customer;
@Column(name = "checkNumber", length = 50)
private String checkNumber;
// 构造函数, equals(), hashCode(), getter 和 setter 方法
}
然后,Payment 实体将使用:
@EmbeddedId private PaymentId id;
主要区别在于 @EmbeddedId 将复合主键视为一个嵌入式对象,而 @IdClass 将字段分开。
- 为什么要使用
@IdClass?
@IdClass 在以下情况下很有用:
- 需要维护主键定义和实体之间的清晰分离。
- 使用遗留数据库,其中已经定义了复合主键。
总结
@IdClass(PaymentId.class) 告诉 JPA,主键由多个字段 (customer 和 checkNumber) 组成。PaymentId 类作为标识符表示,允许 JPA 正确处理复合主键在实体操作(如持久化、检索和比较)中的各种情况。










