Reputation: 3327
I have a hibernate application, where I want to persist an owner.
One owner can have many animals
(inside Owner entity)
@OneToMany(mappedBy = "owner")
private List<Animal> animals;
(inside Animal entity)
@ManyToOne
private Owner owner;
I have a repository, where I persist my owner,
@Override
public Owner create(String name, String email, int age,
List<Animal> animals) {
Owner owner = new Owner(name, email, age, animals);
for(Animal animal: animals){
animal.setOwner(owner);
}
getEntityManager().persist(owner);
return owner;
}
}
the owner is persisted correctly, but the foreign key is not set in the animal table.
I used the debugger to check that the owner is set correctly for the animal which it is.
First, I tried persisting the animal which caused an error
for(Animal animal: animals){
animal.setOwner(owner);
getEntityManager().persist(animal)
} //caused an error
so I thought about using a type of cascade, to make sure, the animal gets the Owner id into the database,
@OneToMany(cascade = CascadeType.ALL)
private List<Animal> animals;
this caused an error as well
"cause": {
"detailMessage": "detached entity passed to persist: com.tolboll.zoo.data.entities.Animal",
"stackTrace": [],
"suppressedExceptions": []
},
how can i make it so, that the owner is correctly persisted into the animal entity?
EDIT:
here is the JSON body passed in
{
"name": "kristoffer",
"email": "[email protected]",
"age": 23,
"animals": [{
"id": 1,
"name": "Simba",
"weight": 110,
"species": {
"id": 1,
"name": "Lion"
}
}]
}
Upvotes: 1
Views: 68
Reputation:
You get that error because you are trying to persist a detached entity: Animal.
Solution
In the Owner entity, leave as it is (although CascadeType.MERGE
is enough):
@OneToMany(cascade = CascadeType.ALL)
private List<Animal> animals;
Then, in the create
method, replace persist
by merge
:
getEntityManager().merge(owner);
The reason for that is the merge operation that you need for the animals
list.
Upvotes: 1