I have 2 entities : Account and AccountRole.
public class Account {
private AccountRole accountRole;
@ManyToOne(cascade = Ca
You cannot pass a datached entity to persist, there is no way. But you don't need to.
You want to persist an Account independently of the AccountRole(which is already persisted). In order to achieve this, simply remove cascading from @ManyToOne in the child entity (Account in this case):
public class Account {
private AccountRole accountRole;
@ManyToOne // no cascading here!
public AccountRole getAccountRole() {
return accountRole;
}
See my explanation here, why: https://stackoverflow.com/a/54271569/522578
It looks like you leave the transaction during your processing, so the accountRole gets detached, or it is already detached for other reasons.
A call to entityManager.merge(accountRole) before calling entityManager.persist(account) should fix it.
EDIT: Unfortunately, if you cannot be sure if the accountRole already exists in the DB, you will have to check it by querying. If it exists - merge, if not - persist. It is indeed a hassle, but I have not yet seen a better workaround.
EDIT2: The entity you pass to the merge method will remain detached - the managed entity will be returned by the merge, so you would need to merge first, then set the reference on the account to the return value of the merge.
Just replace the
entityManager.persist(account);
with:
entityManager.merge(account);
And allow merge cascading:
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.EAGER)
public AccountRole getAccountRole() {
return accountRole;
}
Because merge does this:
If your entity is new, it's the same as a persist(). But if your entity already exists, it will update it.