Hibernate的映射关系中,多对一的映射关系只有多对一单向映射关系。
映射原理:在“多”的一端加入一个外键,指向“一”的一端,由多的一端维护关联关系。“多”的一端持有“一”的一端的引用。
下面举例用户(User)和分组(Group),多个用户可以对应同一个分组,在多对已个映射关系中,是具有方向性的,即可以通过用户(User)看到分组(Group),但从分组不能看到用户。数据库表中,需要在User表中添加一个外键来指向分组。
User.java
package com.suo.bo;
/**
* User entity. @author MyEclipse Persistence Tools
*/
public class User implements java.io.Serializable {
// Fields
private Integer id;
private String name;
private Group group;
// Constructors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
}
User.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.suo.bo.User" table="user" catalog="hibernate">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="increment" />
</id>
<!-- group是User类属性 ,表达该对象与Group是多对一的关系-->
<many-to-one name="group" class="com.suo.Group" column="groupId"></many-to-one>
<property name="name" type="java.lang.String">
<column name="name" />
</property>
<property name="groupId" type="java.lang.Integer">
<column name="groupId" />
</property>
</class>
</hibernate-mapping>
Group.java
package com.suo.bo;
/**
* Group entity. @author MyEclipse Persistence Tools
*/
public class Group implements java.io.Serializable {
// Fields
private Integer id;
private String name;
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Group.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.suo.bo.Group" table="group" catalog="hibernate">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="increment" />
</id>
<property name="name" type="java.lang.String">
<column name="name" />
</property>
</class>
</hibernate-mapping>