Home EclipseLink/JPA: Merge on detached object tree causes primary key violation in child object
Reply: 0

EclipseLink/JPA: Merge on detached object tree causes primary key violation in child object

user2540 Published in March 23, 2018, 10:16 pm

I have a problem with JPA and detached entity objects passed from outside the application via JSON deserialization.

I deserialize an object graph from JSON (passed through a HTTP POST request) and then try to update an existing entity from it.

As far as I understand JPA, using EntityManager.merge() on an object should automatically and recursively (depending on cascade) attach it and issue an UPDATE to the DB for all the objects in the tree. However, this apparently only works well for 1) a single entity with no children or 2) the topmost entity in an object graph.

For the child entities, JPA will always issue an INSERT INTO, regardless if the object is already there, and thus run into a primary key violation.

What am I doing wrong?

The relevant part of the implementation is this:

In AdminResource.java:

protected CustomerConfigDAO customerConfigDao; // wrapper for the JPA persistence

public void storeConfigurationData(CustomerConfigEntity config) {
    customerConfigDao.update(config); // calls EntityManager.merge(...)

In CustomerConfigEntity.java:

public class CustomerConfigEntity implements Serializable {

    private String customerID;

    @OneToOne(mappedBy = "customerConfigEntity", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private DefaultValues defaultValues;

    /* ... snip ... */

    public void fixBackReference() {
        if(this.defaultValues != null)

In DefaultValues.java:

public class DefaultValues implements Serializable {

    @JoinColumn(name = "customerID", referencedColumnName = "cloudID")
    private CustomerConfigEntity customerConfigEntity;

    /* ... snip ... */


Someone suggested to drop the bi-directional one-to-one relationship in favour of a uni-directional one, but since customerConfigEntity is both the foreign AND the primary key in DefaultValues, removing it would require me to introduce a surrogate key. I did this by introducing an auto-incremented key, but the result was that JPA would create a new record in DEFAULTVALUES whenever a CustomerConfigEntity was saved.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299884 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO