参考链接:JPA Primary Key
业务场景:
实体类Aaabc中需要将id1、id2作为联合主键来使用
方式一:使用@IdClass
首先定义IdClass类
import lombok.Data;
import java.io.Serializable;@Data
public class AaabcIdClass implements Serializable {private String id1;private Integer id2;
}
实体类中指定IdClass,并且使用多个@Id:
import lombok.Data;
import java.io.Serializable;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonInclude;@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@Entity
@Table(name = "Aaabc")
@IdClass(AaabcIdClass.class)
public class Aaabc implements Serializable {@Id@Column(name = "id1", nullable = true, length = 36)private String id1;@Id@Column(name = "id2", nullable = true)private Integer id2;@Column(name = "name", nullable = true, length = 200)private String name;
}
方式二:使用@EmbeddedId与@Embeddable
定义Embeddable类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import javax.persistence.*;
import java.io.Serializable;@Data
@AllArgsConstructor
@NoArgsConstructor
@Embeddable
public class AaabcEmbeddedId implements Serializable {private String id1;private Integer id2;
}
实体类更新为:
import lombok.AllArgsConstructor;
import lombok.Data;
import javax.persistence.*;
import lombok.NoArgsConstructor;@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Aaabc {@EmbeddedId// @AttributeOverrides({@AttributeOverride(name = "id1", column = @Column(name = "id1")), @AttributeOverride(name = "id2", column = @Column(name = "id2"))})private AaabcEmbeddedId id12;@Column(name = "name", nullable = true, length = 200)private String name;
}
持久化实体类对象
public Aaabc saveAaabc() {Aaabc bo = new Aaabc();// bo.setId1("1");// bo.setId2(2);bo.setId12(new AaabcEmbeddedId("1", 2));bo.setName("name1");return aaabcRepository.saveAndFlush(bo);}
控制台输出:
Hibernate: selectaaabc0_.id1 as id1_0_0_,aaabc0_.id2 as id2_0_0_,aaabc0_.name as name3_0_0_ fromAaabc aaabc0_ whereaaabc0_.id1=? and aaabc0_.id2=?
Hibernate: insert intoAaabc(name, id1, id2) values(?, ?, ?)
可见联合主键生效