这里举了皇帝和大臣的例子,天子只有一个,而诸侯多的不胜计数。
实体:
package uni.one2many;
import java.util.HashSet;
import java.util.Set;
public class Emperor {
private int id;
private String name;
private Set<Minister> ministers = new HashSet<Minister>();
public Emperor() {
}
public Emperor(int id, String name, Set<Minister> ministers) {
super();
this.id = id;
this.name = name;
this.ministers = ministers;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Minister> getMinisters() {
return ministers;
}
public void setMinisters(Set<Minister> ministers) {
this.ministers = ministers;
}
}
package uni.one2many;
public class Minister {
private int id;
private String name;
public Minister() {
}
public Minister(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
hbm配置文件:
<hibernate-mapping>
<class name="uni.one2many.Emperor">
<id name="id" column="did">
<generator class="native" />
</id>
<property name="name" type="string" column="name"></property>
<!-- confirure the uniredirection association -->
<set name="ministers" >
<key column="id" not-null="true"></key>
<one-to-many class="uni.one2many.Minister"/>
</set>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="uni.one2many.Minister">
<id name="id" column="did">
<generator class="native" />
</id>
<property name="name" type="string" column="name"></property>
</class>
</hibernate-mapping>
测试文件:
public class Test {
@org.junit.Test
public void testAdd() {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.getCurrentSession();
session.beginTransaction();
Minister m1 = new Minister();
m1.setName("廉颇");
Minister m2 = new Minister();
m2.setName("蔺相如");
Emperor emperor = new Emperor();
emperor.setName("齐威王");
emperor.getMinisters().add(m1);
emperor.getMinisters().add(m2);
session.save(emperor);
session.save(m1);
session.save(m2);
session.beginTransaction().commit();
}
}
测试结果:
ibernate: insert into Emperor (name) values (?)
Hibernate: insert into Minister (name, id) values (?, ?)
Hibernate: insert into Minister (name, id) values (?, ?)
Hibernate: update Minister set id=? where did=?
Hibernate: update Minister set id=? where did=?
这种映射关系在保存的过程中需要先将一的(主控方)一方先加以保存,否则会出现异常。我们可以对这种异常加以分析,从这种关系生成的表结构可以看出,在Minister的表中有一个指向Emperor的外键,由此可以推测出,如果这个外键有了非空约束,那么再存储Minister的过程中必然会出现引用为空的异常。