Reputation: 1404
Here is example:
@Entity(name="Cat")
public class Cat
{
@ManyToOne
@JoinColumn(name="FoodId",nullable=true)
public Food getFood()
{
// code
...
}
@Entity(name="Food")
public class Food
{
@OneToMany(mappedBy="food",cascade=?
public List<Cat> getCats()
{
// other code
...
}
I want to delete some food entity, so cat.foodId column set to null value for cats, who had this food.
Food fish=new Food()
Cat bazillio=new Cat()
bazillio.food=fish
context.remove(fish)
if (bazilio.food==null) success()
Cascade.ALL in my understanding will delete all cats with this food (or not?) So how solve this task?
Upvotes: 0
Views: 2428
Reputation: 12368
One of the relation should be marked as inverse
. I suppose that would be Food.getCats()
Cascade on the Food-to-Cat relation should be None as Cats are independent of the Food entity justified by the nullable
on Cat.getFood()
.
Deleting the food would then be as simple as Ryan specified..
Upvotes: 2
Reputation: 11475
It's the programmer responsibility to maintain that consistency.
From JPA 2 Spec:
Note that it is the application that bears responsibility for maintaining the consistency of runtime relationships—for example, for insuring that the “one” and the “many” sides of a bidirectional relationship are consistent with one another when the application updates the relationship at runtime.
Upvotes: 1
Reputation: 128829
Load all cats whose food is fish, set each cat's food to null, and then delete the food. You'll need to deal with concurrent inserts of new cats with the food you're deleting. They could make the "delete food" transaction fail.
Upvotes: 2