2. 类关联映射
2.1 Many-to-One //这种关系模型是数据表的多对一关系:这个表的一个外键是引用目标表的主键字段
//例如:职员(employee)和部门(department)的关系【许多职员在一个部门】
两个类的关系:employee has department(department是employee的一个属性)
<many-to-one name="department" column="depart_id"/>
2.2 One-to-One
//当一个表的主键同时是另一个表主键和外键时
//例如:User(id,username,password)与UserInfo(id,...)虽然类不同,但却代表现实中的一个对象
两个类的关系:User, UserInfo 互相有对方
//依赖方UserInfo
<hibernate-mapping package="com.xcz.demo">
<class name="UserInfo">
<id name="id">
<generator class="foreign" >
<param name="property">user</param>
</generator>
</id>
<property name="name" length="50"/>
<property name="sex" length="8"/>
<property name="birthday" />
<property name="cardno" length="20"/>
<one-to-one name="user" constrained="true" cascade="save-update"></one-to-one>
</class>
</hibernate-mapping>
UserInfo的被依赖方User
<hibernate-mapping package="com.xcz.demo">
<class name="User">
<id name="id">
<generator class="uuid.hex" />
</id>
<property name="username" length="20"/>
<property name="userpws" length="20"/>
<one-to-one name="userInfo"/>
</class>
</hibernate-mapping>
【看看执行代码】
@Test
public void one2OneExcute(){
Session session = getCurrSession();
Transaction tr = session.beginTransaction();
//添加被依赖方(User)
// User u = new User();
// u.setUsername("xcz");
// u.setUserpws("123456xcz");
//根据被依赖方(User)添加依赖方(UserInfo)
// UserInfo uin = new UserInfo();
// uin.setId("4028e534396bddf601396bddf9060001");
// uin.setName("谢成志");
// uin.setSex("男");
// uin.setBirthday(new Date());
// uin.setCardno("510922198811280012");
// uin.setUser((User)session.get(User.class, "4028e534396bddf601396bddf9060001"));
// session.save(uin);
System.out.println(session.get(User.class,"4028e534396bddf601396bddf9060001"));
tr.commit();
session.close();
}
2.3 One-to-Many
private Set<Employee> emps;
<set name="emps">
<key column="depart_id" /> <!-- 用于标识多的一方在表中存储本表中的主键的列名 -->
<one-to-many class="Employee" /> <!-- 多的一方的类型 -->
</set>
2.4 Many-to-Many
<set name="users" table="t_u_r">
<key column="role_id" />
<many-to-many column="user_id" class="User" />
</set>
<set name="roles" table="t_u_r">
<key column="user_id" />
<many-to-many column="role_id" class="Role" />
</set>