We have Spring Boot application using a OneToOne annotation and PostgreSQL.
What I want to do is saving a PaymentDO and then add a PaymentBatchJobDO to it (using Spring's JpaRepository). Strangely when trying to save the PaymentBatchJobDO this fails.
The PaymentBatchJobDO is an optional child of PaymentDO. The relation is done using 'shared primary key'. This means PaymentBatchJobDO's paymentId-field becomes same value as PaymentDO's paymentId-field.
Until Hibernate core 5.3.* that worked perfecty but with 5.4.* I get following error:
If I use a H2 database the error does not occur.
There are different ways to implement a OneToOne relationship. If I change to the (probably more typical):
I get following error:
--> paymentbat0_.payment_payment_id does not exist!
If I set hibernate.id.disable_delayed_identity_inserts=true the error does not change in any way.
I tried using hibernate-core in version 5.4.0.CR1 & 2 as well but error occurs there identically. Furthermore I noticed that when I update to hibernate-core 5.4.0 I get newer versions of hibernate-commons-annotations, javaassist an org.jboss:jandex. If I these back to the state used for hibernate-core 5.3.* error is still the same. Thus the error originates definitely in the hibernate-core 5.4.* version.
Since it is a Spring Application I use SimpleJpaRepository's save() method. As I have seen now this method calls EntityManager.merge() (do notice: not persist()) although the object to save is new. When using hibernate-core on versions 5.3.* this properly saved the object.
The fact that EntityManager.merge() is called is, that the ID-field is already filled out. This is a result of the 'shared primary key' used for the one-to-one relation.
My question is thus: Have the rules using EntityManager.merge changed? Was it just luck the old code worked or should EntityManager.merge work lenient enough to check that the object is not yet saved and persist it properly? (In Hibernate's Session.merge-Javadoc I read: "If the given instance is unsaved, save a copy of and return it as a newly persistent instance.")
As a workaround I called EntityManager.persist() instead of SimpleJpaRepository's save() which helped. Nevertheless it is bad practice to mix both APIs.
Spring Boot application using PostgreSQL