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

Spring boot : Referential integrity constraint violation

您好,我遇到了这个错误,none 我找到的解决方案有效。 我有一个购物车实体:

@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": "ero@fk.fr",
    "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]

请问我该如何解决这个问题?

您收到 DataIntegrityViolationException 很可能是因为您引用的用户不在数据库中:

您可以在下面的测试中看到场景:

@Test(expected = DataIntegrityViolationException.class)
  public void saveCartWithNonExistentUserMustThrowIntegrityException() {
    // We create a bean to a user that has not been inserted on database
    User user = new User(4815L, "Alfonso", "Cuaron", "aq@academy.com");

    Cart cart = new Cart("in-progress", user, Arrays.asList("1234", "1234"), 10);
    Cart cartSaved = cartRepository.save(cart); // Exception is thrown
  }

  @Test
  public void saveCartWithExistentUserMustSucceed() {
    User user = new User("Alfonso", "Cuaron", "aq@academy.com");
    // We ensure user is persisted on database
    User existentUser = userRepository.save(user);
    // Now User.id reference exist in database
    Cart cart = new Cart("in-progress", existentUser, Arrays.asList("1234", "1234"), 10);
    Cart cartSaved = cartRepository.save(cart);

    Assert.assertNull(cartSaved.getId()); // Cart is persisted
  }