Hibernate关系映射配置

一对一:

// 有外键
<many-to-one name="idCard" class="com.IdCardBean" unique="true">
  <column name="cardId" />
</many-to-one>
// 无外键
<one-to-one name="user" class="com.UserBean" property-ref="idCard" lazy="false" />

一对多:

<set name="users">
  <key>
    <column name="userId" />
  </key>
  <one-to-many class="com.UserBean" />
</set>

多对一:

<many-to-one name="role" class="com.RoleBean">
  <column name="roleId" />
</many-to-one>

多对多(中间表course_student不需配置,注意:中间表的主键必须是复合主键,不应包含自增长主键):

<set name="students" table="course_student" inverse="false" cascade="none" lazy="true"> 
   <key column="courseId"/>   
   <many-to-many column="studentId" class="com.CourseBean" />  
</set>
<set name="courses" table="course_student" inverse="false" cascade="none" lazy="true"> 
   <key column="studentId"/>   
   <many-to-many column="courseId" class="com.StudentBean" />  
</set>

相关推荐