[size=13]假设我们要实现一个简单的从Parent到Child的<one-to-many>关联。 [/size]
如果在使用单向一对多关联,即只在Parent方配置关联。
[code]<set name="children">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>
[/code]
如果我们运行下面的代码
[code]Parent p = .....;
Child c = new Child();
p.getChildren().add(c);
session.save(c);
session.flush();
[/code]
Hibernate会产生两条SQL语句:
一条INSERT语句,为c创建一条记录
一条UPDATE语句,创建从p到c的连接
这样做不仅效率低,而且违反了列parent_id非空的限制。我们可以通过在集合类映射上指定not-null="true"来解决违反非空约束的问题:
这种现象的根本原因是从p到c的连接(外键parent_id)没有被当作Child对象状态的一部分,因而没有在INSERT语句中被创建。因此解决的办法就是把这个连接添加到Child的映射中。
在Child的配置文件中加入
[code]<many-to-one name="parent" column="parent_id" not-null="true"/>[/code]
(我们还需要为类Child添加parent属性)
使之变为双向的一对多关系
现在实体Child在管理连接的状态,为了使collection不更新连接,我们使用inverse属性。
[code]<set name="children" inverse="true">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>[/code]
下面的代码是用来添加一个新的Child
[code]Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);
session.save(c);
session.flush();[/code]
现在,只会有一条INSERT语句被执行!
如果在使用单向一对多关联,即只在Parent方配置关联。
[code]<set name="children">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>
[/code]
如果我们运行下面的代码
[code]Parent p = .....;
Child c = new Child();
p.getChildren().add(c);
session.save(c);
session.flush();
[/code]
Hibernate会产生两条SQL语句:
一条INSERT语句,为c创建一条记录
一条UPDATE语句,创建从p到c的连接
这样做不仅效率低,而且违反了列parent_id非空的限制。我们可以通过在集合类映射上指定not-null="true"来解决违反非空约束的问题:
这种现象的根本原因是从p到c的连接(外键parent_id)没有被当作Child对象状态的一部分,因而没有在INSERT语句中被创建。因此解决的办法就是把这个连接添加到Child的映射中。
在Child的配置文件中加入
[code]<many-to-one name="parent" column="parent_id" not-null="true"/>[/code]
(我们还需要为类Child添加parent属性)
使之变为双向的一对多关系
现在实体Child在管理连接的状态,为了使collection不更新连接,我们使用inverse属性。
[code]<set name="children" inverse="true">
<key column="parent_id"/>
<one-to-many class="Child"/>
</set>[/code]
下面的代码是用来添加一个新的Child
[code]Parent p = (Parent) session.load(Parent.class, pid);
Child c = new Child();
c.setParent(p);
p.getChildren().add(c);
session.save(c);
session.flush();[/code]
现在,只会有一条INSERT语句被执行!