Cascade.ALL非拥有实体侧 [英] Cascade.ALL from non-owning entity side

查看:172
本文介绍了Cascade.ALL非拥有实体侧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个@ManyToMany(双向)项和类别之间的关系。

I have a @ManyToMany (bi-directional) relationship between Item and Category.

class Item {
  @ManyToMany(cascade = CascadeType.ALL)
  Collection<Category> categories=new ArrayList<Category>();
}

class Category {
  @ManyToMany(mappedBy="categories", cascade = CascadeType.ALL)
  Collection<Item> items=new ArrayList<Item>();
}

我已经在两个指定CascadeType.ALL。项目是所有者。多对多关系将使用第三个表(Item_Category)映射

I have specified CascadeType.ALL on both. Item is the owner. ManyToMany relationship would be mapped using a third table (Item_Category)


  1. 当我创建一个项目,并添加类别到该项目,并保存该项目内的所有类别获得持续的项目。也是必要的条目在连接表(如预期)进行。

  1. When i create an item and add categories to that item and save the item all the categories within that item get persisted. Also necessary entries are made in the join table (as expected).

然而,当我创建一个类别,并添加新的项目,它和我保存类别我看到必要的条目项和类别表所做但Item_Category没有插入连接表。其结果,不正确创建的关联。

However, when i create a category and add new items to it and i save the category i see that necessary entries are made in Item and category tables but no inserts in the Item_Category join table. As a result, the association is not created correctly.

这是预期的行为?这意味着关联表将条目只有当我们在添加项目类别,项目是关系的所有者?

Is this expected behavior? Meaning the association table will have entries only if we add categories in Item as Item is the owner of the relationship?

推荐答案

您正在期待魔法,Hibernate是不是这样。保存破对象模型会留下的东西打破。如果项目和类别有双向关系,那么你必须的总是的设置关系的两端。仅仅因为你有Hibernate并不意味着你的code可以偷懒。

You're expecting magic, and Hibernate isn't that. Saving a broken object model will leave things broken. If Item and Category have a bidirectional relationship, then you must always set both ends of the relationship. Just because you have Hibernate doesn't mean your code can be lazy.

要换个说法,你永远不会写code这样的,并期望它的工作,你会(假设工作断言关键字)<? / p>

To put it another way, you'd never write code like this and expect it to work, would you (assuming a working assert keyword)?

Category c = new Category();
Item i = new Item();
c.getItems().add(i);
assert i.getCategories().contains(c);

如果没有,为什么你希望当您添加Hibernate的组合它的工作?

If not, why do you expect it to work when you add Hibernate to the mix?

这篇关于Cascade.ALL非拥有实体侧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆