Ano*_*ick 0 hibernate-mapping spring-data-jpa spring-boot
您好,我遇到了这个错误,我找到的解决方案都不起作用。我有一个购物车实体:
@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;
}
Run Code Online (Sandbox Code Playgroud)
和一个 User 实体
@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>();
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用以下 JSON 传递 POST 请求时:
{
"status": "in-progress",
"usr": {
"id": 1,
"firstname": "jhon",
"lastname": "koer",
"email": "ero@fk.fr",
"phone": "078542163"
},
"productsBarcode": [
"3029330003533",
"3029330003533"
]
}
Run Code Online (Sandbox Code Playgroud)
但我收到这个错误:
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]
Run Code Online (Sandbox Code Playgroud)
请问我该如何解决这个问题?
您收到的消息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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12812 次 |
| 最近记录: |