hibernate配置文件中有这么一个属性inverse,它是用来指定关联的控制方的。
inverse属性默认是false,若为false,则关联由自己控制,若为true,则关联由对方控制。
一个Parent有多个Child,一个Child只能有一个Parent。
package com.xian;
public class Child {
private Long id;
private String name;
private Parent parent;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.xian.Child" table="child">
<id name="id" column="childId">
<generator class="native" />
</id>
<property name="name" type="string"></property>
<many-to-one name="parent" column="parentId" not-null="true">
</many-to-one>
</class>
</hibernate-mapping>
package com.xian;
import java.util.HashSet;
import java.util.Set;
public class Parent {
private Long id;
private String name;
private Set children = new HashSet();
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set getChildren() {
return children;
}
public void setChildren(Set children) {
this.children = children;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class name="com.xian.Parent" table="parent">
<id name="id" column="parentId">
<generator class="native"></generator>
</id>
<property name="name" type="string"></property>
<set name="children" inverse="true">
<!-- 此处inverse设置为true,则关联的控制方交给了child,一对多关联一般都将控制方交给多端 -->
<key column="parentId" not-null="true"></key>
<one-to-many class="com.xian.Child"/>
</set>
</class>
</hibernate-mapping>
Parent p = new Parent();
p.setName("parent");
Child c = (Child) session.load(Child.class, 4l); //原child表中已存在id=4的child
p.getChildren().add(c); // 我希望用parent端来修改关联,即将id=4的child的外键变为现在这个parent的主键值
session.save(p); //这里保存parent,同时希望关联也得到修改
但是我们发现parent确实保存了,而child的外键还是原值,没有关联到我们现在的外键
原因就是我们将关联的控制方交给了child端,这样一来parent就不能够控制关联了。
Parent p = new Parent();
p.setName("parent");
Child c = (Child) session.load(Child.class, 4l);
c.setParent(p); //这样由child端修改关联就ok了
session.save(p);