参考链接: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);
}
控制台输出:文章来源:https://www.toymoban.com/news/detail-682129.html
Hibernate:
select
aaabc0_.id1 as id1_0_0_,
aaabc0_.id2 as id2_0_0_,
aaabc0_.name as name3_0_0_
from
Aaabc aaabc0_
where
aaabc0_.id1=?
and aaabc0_.id2=?
Hibernate:
insert
into
Aaabc
(name, id1, id2)
values
(?, ?, ?)
可见联合主键生效文章来源地址https://www.toymoban.com/news/detail-682129.html
到了这里,关于JPA实体类中使用联合主键的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!