Spring Boot:违反参照完整性约束

时间:2019-03-03 20:34:51

标签: spring-boot spring-data-jpa hibernate-mapping

您好,我遇到此错误,但发现没有一种解决方案有效。 我有一个购物车实体:

@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]

请问该如何解决?

1 个答案:

答案 0 :(得分:0)

您收到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
  }