Spring Boot中使用JPA默认集成了Hibernater,当我们使用单主键的@Entity还是比较方便的,只需要加上@Id注解即可,那如果遇到两个列形成联合主键的场景,该如何定义@Entity呢?下文即为实践。

定义联合主键

import javax.persistence.Embeddable;
import java.io.Serializable;

//要在类上使用@Embeddable注解,标识其为一个增强的主键类
@Embeddable
//一定要实现Serializable序列化接口
public class VerifyResultPK implements Serializable{
//两个成员变量,即为联合主键列
private String cdaname;
private Long cdaxh;
//建议声明2个构造方法,一个无参,一个全参
public VerifyResultPK() {
}

public VerifyResultPK(String cdaname, Long cdaxh) {
this.cdaname = cdaname;
this.cdaxh = cdaxh;
}
//省略getter,setter
}

在Model上使用联合主键

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import java.sql.Timestamp;

@Entity
@Table(name = "TAS_CDAYZ_YZJG")
public class VerifyResultModel implements Serializable{
//使用@EmbeddedId注解,表明这是一个增强的主键
@EmbeddedId
VerifyResultPK key;
private Boolean yzzt;
private Integer cws;
private Long yzxh;
private Timestamp yzsj;
//构造方法里处理主键类的赋值
public VerifyResultModel(String cdaname, Long cdaxh, Boolean yzzt, Integer cws, Long yzxh, Timestamp yzsj) {
VerifyResultPK key = new VerifyResultPK(cdaname,cdaxh);
this.key = key;
this.yzzt = yzzt;
this.cws = cws;
this.yzxh = yzxh;
this.yzsj = yzsj;
}

//省略getter,setter
}

END