开发者

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开发者_StackOverflow understanding will delete all cats with this food (or not?) So how solve this task?


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)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜