和多对一关联映射是非常相似的,并且,都是在多的一端加外键。不同的是,多对一是在多端维护,而一对多是在一端维护关系。
例如,Person和Orgnization,在多对一中是在Person中维护关系;而一对多是在Orgnization端维护关系。
实体设计中,要在Orgnization的一端加上set
用来放置多个Person。
实体Orgnization:
public class Orgnization {
private int id;
private String name;
private String sn;
private String description;
private Set person;
}
实体Person:
public class Person { private int id; private String name; private String sex; private String address; private String duty; private String phone; private String description; }
Hbm.xml文件:
Orgnization.hbm.xml
<hibernate-mapping> <class table="T_Orgnization" name="com.oa.model.Orgnization"> <id access="field" name="id"> <generator class="native"/> </id> <property name="name" access="field"/> <property name="sn" access="field"/> <property name="description" access="field"/> <set access="field" lazy="false" inverse="true" name="person"> <key column="pid"/> <one-to-many class="com.oa.model.Person"/> </set> </class> </hibernate-mapping>Person.hbm.xml
<hibernate-mapping> <class table="T_Person" name="com.oa.model.Person"> <id access="field" name="id"> <generator class="native"/> </id> <property name="name" access="field"/> <property name="sex" access="field"/> <property name="address" access="field"/> <property name="duty" access="field"/> <property name="phone" access="field"/> <property name="description" access="field"/> </class> </hibernate-mapping>
这样的配置,就实现了一对多的关联
在保存的时候,应该先保存Person,在把Person设置到Orgnization的set中,最后保存Orgnization
Set set = new HashSet();
Person p1 = new Person();
p1.setName("p1");
session.save(p1);
set.add(p1);
Person p2 = new Person();
p2.setName("p2");
session.save(p2);
set.add(p2);
Orgnization org = new Orgnization();
org.setName("org");
org.setChildren(set);
session.save(org);
这里可能会有点小问题,保存Orgnization的时候,会发多条语句,影响效率,在以后的文章中,我们会介绍如何避免这个问题,这里不再赘述。