I am using JPA and have the following:
ProductEntity
@Basic
@Column(name = "PRODUCT_ID", nullable = false, length = 128)
private String productId;
@ManyToOne
@JoinColumn(name = "PARENT_ID")
private ProductEntity parent;
As you can see the product table can have a parent. Effectively a parent child relationship.
I have a product saved in the database, then I add some child products, each having the same parent.
The child Products have ProductEntity parent = the parent Product;
ProductEntity parentProductEntity = ...
ProductEntity childProductEntity1 = ...
ProductEntity childProductEntity2 = ...
em.persist(parentProductEntity);
childProductEntity1.setParent(parentProductEntity);
childProductEntity2.setParent(parentProductEntity);
em.merge(childProductEntity1);
Data (it never inserts the last two child rows)
ID PRODUCT_ID PARENT_ID
1 1 null
2 2 1
3 3 1
Problem
I then try save each child Product. But I get an error indicating that there is a duplicate key (productId). When saving the child, it is trying to save a duplicate entry of the parent too.
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "t_osm_product_product_id_uindex"
Question
How must I change what I am doing to successfully save each child Product?
Thanks
You can do that selectively with EntityManager. detach() , or en masse with EntityManager. clear() .
your entity should look like this
@Id
Long ID;
@Column(name = "PRODUCT_ID", nullable = false, length = 128)
private String productId;
@ManyToOne
@JoinColumn(name = "PARENT_ID")
private ProductEntity parent;
everything else seems fine in your code.
Data will look like this in the database
ID PRODUCT_ID PARENT_ID
1 abc null
2 def 1
3 xyz 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With