Issue
I have two entity classes, named Product and ComboProduct. Product contains all the information about a particular product and has a Primary Key productId
. ComboProduct holds a list with a @OneToMany
relationship to the Product and has a primary key named comboProductId
. When I create multiple Comboproduct
instances with the same set of products, I get the following DataIntegrityViolationException
:
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long productId;
@OneToOne
private MasterProduct masterProduct;
@NotBlank
private String productName;
private String productDescription;
private Double productSellingPrice; // mrp
private Double productOfferPrice; // price at which the user sells
private Double productPurchasePrice;
private float totalTaxPercentage;
private float productMargin;
@OneToOne
private MerchantStore store;
@ManyToOne
private ComboProduct comboProduct; @Entity
public class ComboProduct {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long comboProductId;
private String comboProductKey;
@OneToMany
private List<Product> products;
@NotBlank
private String comboName;
private String comboDescription;
org.springframework.dao.DataIntegrityViolationException:
could not execute statement; SQL [n/a];
constraint [UK_nm4dyaqp2f780nx73vq9abbw3];
nested exception is org.hibernate.exception.ConstraintViolationException:
could not execute statement\n\t
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:298)\n\t
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:255)\n\t
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:538)\n\t
at org.springframework.transaction.support.
How can I resolve this?
Solution
as you have modeled a One-to-Many relationship, you defined that one combo is associated to multiple products. But products can only be assigned to one combo.
If you want products to be able to belong to multiple combos, you would need to model a Many-to-Many relationship. That would of course also imply to have a respective mapping table on the database.
Answered By - cobz