MyBatis关联查询(级联查询)

MyBatis支持通过association配置进行关联查询,也称为级联查询。主要有一对一(association)、一对多(collection)和多对多(collection)三种关联查询。一对一(association):

<resultMap id="UserSimpleResultMap" type="User">
  <association property="account" javaType="Account">
    <id column="uid" property="uid"/>
    <result column="name" property="name"/>
  </association>
</resultMap> 

<select id="getUser" resultMap="UserSimpleResultMap">
  select * from user u left join account a on u.id = a.uid where u.id = #{id}
</select>

一对多(collection):

<resultMap id="UserRolesResultMap" type="User">
  <collection property="roles" ofType="Role">
    <id column="rid" property="rid"/>
    <result column="rolename" property="name"/>
  </collection>  
</resultMap>

<select id="getUserRoles" resultMap="UserRolesResultMap">
 select u.*, r.rid, r.name as rolename 
   from user u 
   left join user_role ur on u.id = ur.uid 
   left join role r on r.rid = ur.rid
  where u.id = #{id}
</select>   

多对多(collection):

<resultMap id="StudentSubjectsResultMap" type="Student">
  <collection property="subjects" ofType="Subject">
    <id column="sid" property="sid"/>
    <result column="name" property="name"/> 
  </collection>
</resultMap>

<select id="getStudentSubjects" resultMap="StudentSubjectsResultMap">
select s.*, sub.sid, sub.name as subj_name 
  from student s 
  left join student_subject ss on s.id = ss.sid 
  left join subject sub on sub.sid = ss.sid 
  where s.id = #{id}
</select> 

通过配置association和collection实现一对一、一对多和多对多的关联查询。

collection内部的ofType用来指定集合内元素的类型,然后配置连接查询获取关联数据填充集合。关联查询可以解决实体间的依赖关系,避免多次查询获取关联数据的问题。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论