IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST:

Hello,
I am trying to insert data in two entities at the same time, but on certain occasions it gives the error of “IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST:” and I don’t really know how to fix it, I would greatly appreciate your help.

Hi,
This error usually happens when you’ve created in your code two new entities: A and B, and set link from A to B.
They you are trying to commit “A” to the database, but forgot to commit B with it.

Such connected graphs should be saved to the database only together at once.

Hi,
In this case they are linked by a composition and it does not happen always, sometimes it does and sometimes it does not, although within a BProc it happens more often.
Is there any solution for this? Thank you

The solution is: to commit new linked entities always together.

OR

First commit the entity B (referenced entity), obtain updated reference to the saved entity.
And then set entityA.setB(committedB) link in the entity A.
Then commit A.