在这里举了一个不太恰当的例子:双亲和孩子。当然举这个例子也有一定的道理,一个孩子至少有两个parent,但是例子只是例子,重点不是例子而是配置方法。下面我们看一下配置的详细步骤:
实体:
package uni.many2one;
public class Child {
private int id;
private String name;
public Child(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Child() {
}
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;
}
}
package uni.many2one;
public class Parent {
private int id;
private String name;
private Child child;
public Parent() {
}
public Parent(int id, String name, Child child) {
super();
this.id = id;
this.name = name;
this.child = child;
}
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 Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
hbm配置文件:
<hibernate-mapping>
<class name="uni.many2one.Child">
<id name="id" column="did">
<generator class="native" />
</id>
<property name="name" type="string" column="name"></property>
</class>
</hibernate-mapping>
<hibernate-mapping>
<!-- <class name="org.hibernate.wk.Student" dynamic-insert="true" dynamic-update="true"> -->
<class name="uni.many2one.Parent">
<id name="id" column="did">
<generator class="native" />
</id>
<property name="name" type="string" column="name"></property>
<!-- configure the many to one association -->
<many-to-one name="child" column="child"></many-to-one>
</class>
</hibernate-mapping>
测试文件:
public void testAdd() {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.getCurrentSession();
session.beginTransaction();
Child c1 = new Child();
c1.setName("child1");
Parent mother = new Parent();
mother.setName("Mother");
mother.setChild(c1);
Parent father = new Parent();
father.setName("Daddy");
father.setChild(c1);
session.save(c1);
session.save(mother);
session.save(father);
session.beginTransaction().commit();
}
测试结果:
Hibernate: insert into Child (name) values (?)
Hibernate: insert into Parent (name, child) values (?, ?)
Hibernate: insert into Parent (name, child) values (?, ?)
这里我没有贴出来表的结构,因为表hibernate会自动生成的,多以就没有浪费地方。
hibernate关联关系映射的配置中务必要搞清楚谁是主动配置方,谁是被配置的,如果搞不清楚很容易在实体操作的时候出现错误。尤其是在保存实体的时候,很容易出现引用为空的情况。