Spring Boot JPA 使用以及设置多个主键

一、spring data jpa的使用

推荐以下两篇文章

spring data jpa的使用
spring-boot-jpa 使用

二、设置多个主键(复合主键)

下面介绍两种方法:

第一种:@IdClass来设置多个主键

1、先写一个包含主键的类

@Data
public class PrimaryKey implements Serializable {

    private Integer id;

    private Integer userId;
}

2、在Entity类中,按照如下方式使用

@Data
@Entity
@Table(name = "xx")
@IdClass(PrimaryKey.class)
@EqualsAndHashCode(callSuper = true)
@DynamicUpdate
public class MyEntity{

    /**
     * @description 主键
     */
    @Id
    @Column(name = "id", nullable = false)
    private Integer id;

    /**
     * @description 主键
     */
    @Id
    @Column(name = "user_id", nullable = false)
    private Integer userId;

}

参考:

Spring Boot JPA 复合主键只查询部分主键

第二种:@Embeddable和@EmbeddedId来设置联合主键

推荐这篇文章:两个属性定义一个主键:JPA中的联合主键

猜你喜欢

转载自blog.csdn.net/xx326664162/article/details/80053719