Spring启动:参照完整性约束违规

问题描述 投票:0回答:1

你好,我正面临这个错误,没有找到解决方案。我有一个Cart实体:

@Data
@Entity
public class Cart {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String status;
  @ManyToOne(cascade = CascadeType.MERGE)
  @JoinColumn(name = "usr_id", nullable = false)
  private User usr;
  @ElementCollection(targetClass=String.class)
  private List<String> productsBarcode = new ArrayList<>();
  private long nutritional_score;
}

和用户实体

@Entity
@Data
public class User {
    @Id
    @GeneratedValue
    private Long id;
    private String firstname;
    private String lastname;
    private String email;
    private String phone;
    @JsonIgnore
    @OneToMany(mappedBy = "id",cascade=CascadeType.ALL)
    private List<Cart> carts = new ArrayList<Cart>();
}

当我尝试使用以下JSON传递POST请求时:

{
  "status": "in-progress",
  "usr": {
    "id": 1,
    "firstname": "jhon",
    "lastname": "koer",
    "email": "[email protected]",
    "phone": "078542163"
  },
  "productsBarcode": [
    "3029330003533",
    "3029330003533"
  ]
}

但我得到这个错误:

org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: 
"FK8TNAV1OMIP1EBGI23DBBO8B8T: PUBLIC.CART FOREIGN KEY(USR_ID) REFERENCES PUBLIC.USER(ID) (100)"; SQL statement: 
insert into cart (id, nutritional_score, status, usr_id) values (null, ?, ?, ?) [23506-197]

我该如何解决这个问题?

spring-boot spring-data-jpa hibernate-mapping
1个回答
0
投票

您最有可能收到qazxsw poi,因为您可能正在引用不在数据库中的用户:

您可以在以下测试中看到该方案:

DataIntegrityViolationException
© www.soinside.com 2019 - 2024. All rights reserved.