Hibernate一对多映射外键问题 [英] Hibernate one to many mapping foreign key issue

查看:101
本文介绍了Hibernate一对多映射外键问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是休眠的新手。请帮助我理解这一点。



我有Department和Employee对象。部门正在采用级联类型SAVE的员工集合。我创建了部门对象和员工对象。分别说明了dept1和emp1。当我保存dept1对象(具有emp1)时,它将dept1和emp1保存在部门和员工表中除非我在emp1上设置department(dept1),否则不会保存外键。为什么我应该手动设置?不能冬眠呢?是否有任何理由这样做?

解决方案

因为这就是Hibernate文档和JPA规范告诉你这样做的原因。在一个双向关联中,有一个所有者方和一个相反方。所有者方是没有 mappedBy 属性的方。反方是具有 mappedBy 属性的方面。



在双向OneToMany中,所有者方始终很多方面(具有foerign键的方面)。

Hibernate / JPA只关心所有者方面。如果您没有初始化所有者方,则认为该关联不存在。除非你真的知道你在做什么,否则一个好的经验法则是初始化关联的两个方面,以使你的图形具有一致性。

I am new to hibernate. Please help me in understanding this.

I have Department and Employee objects. Department is having employee collection with cascade type SAVE.I have created department object and employee object.lets say dept1 and emp1 respectively.When I save dept1 object(which is having emp1) ,it is saving dept1 and emp1 in department and employee tables with out foreign key.

Unless I am setting department(dept1) on emp1 , it is not saving foreign key. why should i manually set that? can't hibernate do that? Is there any reason for doing that?

解决方案

Because that's how the Hibernate documentation and the JPA spec tells you to do it. In a bidirectional association, there's an owner side, and an inverse side. The owner side is the one which doesn't have the mappedBy attribute. The inverse side is the one which has the mappedBy attribute.

In a bidirectional OneToMany, the owner side is always the many side (the one which has the foerign key).

Hibernate/JPA only cares about the owner side. If you don't initialize the owner side, it considers the association doesn't exist. Unless you really know what you're doing, a good rule of thumb is to initialize both sides of the association, to make your graph of entities coherent.

这篇关于Hibernate一对多映射外键问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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