SpringBoot JPA 建立联合主键和联合唯一性约束

  1. 建立联合主键

在选择需要联合主键的实体类的属性上加上@Id注解

@Entity
public class test {
 
    @Id
    private Long id1;
 
    @Id
    private Long id2;
    
    ...
}
  1. 建立唯一性约束

在实体类上的@Table添加唯一键约束属性uniqueConstraints

@Table(name = "statistics_info",uniqueConstraints= @UniqueConstraint(columnNames="statistics_type"))
@Data
@Entity
public class StatisticsInfo{
  @Column(name = "statistics_time")
  private Long statisticsTime;

  @Column(name = "statistics_type")
  private String statisticsType;

  @Column(name = "statistics_number")
  private Long statisticsNumber;

  @Column(name = "statistics_size")
  private Long statisticsSize;

  @Column(name = "user_id")
  private String userId;
}
  1. 建立联合唯一性约束
@Table(name = "statistics_info",uniqueConstraints= @UniqueConstraint(columnNames={"statistics_type","statistics_time","user_id"}))
@Data
@Entity
public class StatisticsInfo{
  @Column(name = "statistics_time")
  private Long statisticsTime;

  @Column(name = "statistics_type")
  private String statisticsType;

  @Column(name = "statistics_number")
  private Long statisticsNumber;

  @Column(name = "statistics_size")
  private Long statisticsSize;

  @Column(name = "user_id")
  private String userId;
}

有一点需要注意的,UniqueConstraint里面的columnNames值需要根实体类匹配,比如columnNames使用user_id,而private String userId上面没有@Column(name = “user_id”),因为没有匹配上就会报错
报错如下:
Unable to create unique key constraint (statistics_type, statistics_time, user_id) on table statistics_info: database column ‘user_id’ not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)

你可能感兴趣的:(SpringBoot JPA 建立联合主键和联合唯一性约束)