![](/img/trans.png)
[英]Not able to insert data in MySQL 8 DB using Spring Boot and JPA
[英]Insert Into mysql using spring boot Jpa not working
我試圖在 Spring Boot 中使用 JpaRepository 將數據保存到 Mysql 數據庫中,但是我不斷收到以下錯誤,不知道做錯了什么:
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
我的模型類看起來像:
@Entity
@Table(name = "cart")
public class Cart {
@Id
@Column(name = "id", unique = true, nullable = false)
private String id;
@Column(name = "user_id")
private int userId;
@OneToMany(fetch = FetchType.LAZY, targetEntity = User.class)
@JoinColumn(name="user_id", referencedColumnName = "id", insertable = false, updatable = false)
private List<User> user;
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
public Cart() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false, columnDefinition = "integer")
private Integer id;
@Column(name = "name")
private String name;
@Column(name = "email")
private String email;
@Column(name = "phone")
private String phone;
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
我的存儲庫:
@Repository
public interface CartRepository extends JpaRepository<Cart, String> {
}
我做錯了什么,有沒有更好的方法來保存數據?
更新:這是郵遞員使用的數據:
{
"id": "5beeb524-20fc-11ea-978f-2e728ce88125",
"user_id": 1
}
但是,當我記錄上述數據時,它返回上述 id 但 user_id 始終返回 0
購物車的 ID 不是自動生成的。
為唯一 id 添加一個生成器。 例如,對於一個字符串,生成器可能是這樣的:
@Id
@GeneratedValue(generator = "uuid")
@Column(name = "id", unique = true, nullable = false)
private String id;
相應地為您的唯一 ID 找到合適的類型和生成器。 我希望它有幫助。
編輯:在看到堆棧跟蹤后,這看起來也有些幫助: 無法執行語句 SQL 約束 [id] 嵌套異常是 org.hibernate.exception.ConstraintViolationException
此外,問題似乎是因為 cart.user_id 是引用 user.id 的外鍵,它違反了一些約束。
將以下內容添加到用戶模型類:
@OneToMany(mappedBy = "user_id", cascade = CascadeType.ALL)
private List<User> users;
並將以下內容添加到購物車模型類:
@ManyToOne
@JoinColumn
private int user_id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.