Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Exception saving parent/children

Tags:

java

database

jpa

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 parent Product has ProductEntity parent = null;
  • 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

like image 810
Richard Avatar asked Dec 07 '18 07:12

Richard


People also ask

How can we prevent saving child objects with JPA?

You can do that selectively with EntityManager. detach() , or en masse with EntityManager. clear() .


1 Answers

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
like image 132
Reza Nasiri Avatar answered Oct 01 '22 11:10

Reza Nasiri