Spring boot: нарушение ограничения ссылочной целостности

0
задан AnotherBrick 3 March 2019 в 20:34
поделиться

1 ответ

Вы получаете 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
  }
0
ответ дан Cristian Colorado 3 March 2019 в 20:34
поделиться
Другие вопросы по тегам:

Похожие вопросы: