XML文件个人书写规范
<!-- users属性,本类与User的一对多关系 -->
格式:?属性,本类与?的??1 属性名
?2 关联对类型
?3 关系
配置模板
多对一:<many-to-one name="" class="" column="" />
一对多(Set):
<set name=""><key column="" />
<one-to-many class=""/>
</set>
多对多(Set):
<set name="" table="">
<key column="" />
<many-to-many class="" column="" />
</set>
经典案例
映射关系
配置详情
Department.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.cust.oa.domain"><class name="Department" table="cust_department"><id name="id"><generator class="native" /></id><property name="name" /> <property name="description" /><!-- users属性,本类与User的一对多关系 --><set name="users"><key column="departmentId"/><one-to-many class="User" /></set> <!-- parent属性,本类与Department(上级)的多对一关系 --> <many-to-one name="parent" class="Department" column="parentId" /> <!-- children属性,本类与Department(下级)的一对多关系 --> <set name="children"><key column="parentId"/><one-to-many class="Department" /></set> </class></hibernate-mapping>
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.cust.oa.domain"><class name="User" table="cust_user"><id name="id"><generator class="native" /></id><property name="loginName" /> <property name="password" /> <property name="name" /> <property name="gender" /> <property name="phoneNumber" /> <property name="email" /> <property name="description" /> <!-- department属性,本类与Department的多对一关系 --><many-to-one name="department" class="Department" column="departmentId" /> <!-- roles属性,本类与Role的多对多关系 --><set name="roles" table="cust_user_role"><key column="userId"/><many-to-many class="Role" column="roleId" /></set> </class></hibernate-mapping>
Role.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.cust.oa.domain"><class name="Role" table="cust_role"><id name="id"><generator class="native" /></id><property name="name" /> <property name="description" /><!-- users属性,本类与User的多对多关系 --><set name="users" table="cust_user_role"><key column="roleId"/><many-to-many class="User" column="userId" /></set> </class></hibernate-mapping>