I am trying to persist data into a Mysql db using JpaRepository in spring boot however I keep getting the following error, not sure what am doing wrong:
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
My Model classes looks like:
@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;
}
}
My repository:
@Repository
public interface CartRepository extends JpaRepository<Cart, String> {
}
What am i doing wrong and is there a better way to persist data?
Update: This is the data am using on postman:
{
"id": "5beeb524-20fc-11ea-978f-2e728ce88125",
"user_id": 1
}
However when i log the above data, it returns the id as above but the user_id always returns 0
The id for cart is not auto-generated.