Spring Boot 2.2.x and OneToOne null identifier?

We have the situation where we have a unidirectional @OneToOne relationship in a Spring Boot 2.2.5 application, migrated from Spring Boot 1.4.x. It’s simple relationship …. a ProductBuild object maintains a OneToOne to a Product. On setting up a new ProductBuild, with an existing (already persisted) Product, the save of the ProductBuild fails with a “null identifier” message.

From what we have been able to find out, one fix is to add @Cascade( cascade=CascadeType.MERGE). This appears to be due to changes between Spring JPA and Hibernate, where on the persist of the ProductBuild, a different code path is taken and an underlying merge() call is being made instead of persist(). This is the smallest possible change, but does have the effect that the underlying Product could be updated, so bear that in mind if you use this type of fix.

Another fix comes from a hint from this link; it point to the use of the Spring Data Persistable interface. In this case, we are given the control of determining if an object is a new object or not, and that apparently has the repository save method use the correct path (merge or persist). Our implementation of the interface is very basic:

    @Transient
    private boolean isNew = true;

    @PostLoad
    protected void setLoaded() {
        isNew = false;
    }

    @Override
    public Integer getId() {
        return standardPluId;
    }

    @Override
    public boolean isNew() {
        return isNew;
    }

This does have the desired effect, and the app now works properly.

Our preference, for our application, is to use the CascadeType.MERGE approach, as it much smaller, and in our case, we have a true one-to-one relationship so we know we won’t have any side effects by the persistence of the Product.

Note that the Product already exists, is already persisted, and has no changes to it in the course of creating the instance of ProductBuild. This all worked in Spring Boot 1.4.x, so we’re scratching our heads a bit on why this happens.

Useful links that led us to our fix (I won’t call it a solution) include:

https://github.com/spring-projects/spring-boot/issues/20181

https://hibernate.atlassian.net/jira/software/c/projects/HHH/issues/HHH-13866

https://hibernate.atlassian.net/browse/HHH-13413?attachmentOrder=asc

About John Woodward

Principal Consultant at Improving Enterprises, Inc. Tesla referral code: https://ts.la/john91435
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

1 Response to Spring Boot 2.2.x and OneToOne null identifier?

  1. Kashan says:

    Thank you,
    Your post helped me fix a similar issue.

Leave a comment