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

本文详细介绍了在实体类中如何使用@Id注解创建联合主键,以及通过@Table注解的uniqueConstraints属性实现单一字段或多个字段的唯一性约束。特别强调了UniqueConstraint中的columnNames值必须与实体类中的字段名匹配,否则将导致数据库错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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)

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值