I have two Entity classes Customer and Product, Where One customer can buy Multiple Products (One to Many Mapping)
@Entity
public class Customer {
@Id
@GeneratedValue
private int id;
private String name;
private String email;
private String gender;
@OneToMany(targetEntity = Product.class,cascade = CascadeType.ALL)
@JoinColumn(name ="cp_fk",referencedColumnName = "id")
private List<Product> products;
}
@Entity
public class Product {
@Id
private int pid;
private String productName;
private int qty;
private int price;
}
Its working fine when One customer having multiple Products.
Issue comes when existing product bought by a customer is also bought by another customer.
Request Payload 1: (It works fine creates a user basant and two products)
{
"customer": {
"name": "Basant",
"email": "b@gmail.com",
"gender": "male",
"products": [
{
"pid": 201,
"productName": "Mobile",
"price": 10000,
"qty": 1
},
{
"pid": 399,
"productName": "Laptop",
"price": 200000,
"qty": 3
}
]
}
}
Request Payload 2 : (This request will give java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '201' for key 'product.PRIMARY')
{
"customer": {
"name": "Santosh",
"email": "s@gmail.com",
"gender": "male",
"products": [
{
"pid": 201,
"productName": "Mobile",
"price": 10000,
"qty": 1
},
{
"pid": 286,
"productName": "clothes",
"price": 40000,
"qty": 2
}
]
}
}
How can we make sure Santosh is also able to buy same Mobile which Basant bought? Could you please help me with this