I have two entity classes Organisation and User with a One To Many relationship (Groovy Code for simplicity!):
@Entity
class Organisation {
@Id Long id
String name
@OneToMany
List<User> users
}
@Entity
class User {
@Id Long id
String username
@ManyToOne(optional=false, cascade = CascadeType.Persist)
Organisation organisation
}
When I create a new user with a new organisation everything works fine:
def user = new User(organisation: new Organisation(...))
But when I take an existing organisation, set it to the organisation attribute to a new user I get an error:
def user = new User(organisation: organisationRepository.findOne(orgId))
userRepo.save(user)
Will result in:
org.hibernate.PersistentObjectException: detached entity passed to persist: Organisation
I know that one cannot call persist on a detached entity. But in that case, since I don't change anything on the organisation entity itself, I thought hibernate would permit it.
I tried to put cascade = {CascadeType.Persist, CascadeType.Merge}
into the ManyToOne annotation, but that ends in the same error.
Is the thing I want to archive not possible with hibernate or do I have a thinking error somewhere?