I have a spring JPA repository that is attempting to do a SELECT on an entity. This entity has a relationship with its parent thus:
User (Parent ) > Addresses > AddressType (Child)
During the course of updating the User
, I want to add An Address
. The Address has a field addressType
that is OneToOne Relationship with an AddressType
Static Data Table (Ie the address type can only be POBOX
or General
) as depicted above.
During the process of UPDATING User
, am adding a new Address
and doing a findByName
of AddressType with the passed in addressType from the incoming User+Address
DTO.
However, When I do a findByName
on AddressType's JPA repository - IT attempts to do an INSERT on the parent Address
first. What this does is cause a IntegrityViolationException since Address is being first inserted WITHOUT an AddressType
which is a mandatory field. I did some research here on SO and found some threads indicating this could be a behavior of entitymanager which is somehow declaring the Address
being added as dirty.
My question is - how can I prevent an INSERT on the parent Address
so that the SELECT on the AddressType
happens on its own?
This is the normal flushing behaviour of JPA. When you change an entity managed by JPA these changes get flushed to the database before a query gets executed.
You did change a User
entity by adding an Address
to it.
To fix that add the Address
only when it is fully constructed, i.e. it's AddressType
is set.
Note: I'm sure this is a duplicate, but I can't find it. But there is this closely related question: JPA auto flush before any query