Artyom Chernetsov
Artyom Chernetsov

Reputation: 1404

How to delete parent entity and set null in child FK column in hibernate?

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

Answers (3)

frictionlesspulley
frictionlesspulley

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..

  1. loading cats where food is set to the specified food
  2. setting the cat.food to null
  3. saving cat instances and deleting the food instance (can be carried out in any order)

Upvotes: 2

Alfredo Osorio
Alfredo Osorio

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

Ryan Stewart
Ryan Stewart

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

Related Questions