> 文档中心 > MyBatis高能——一对一和一对多的方式详解

MyBatis高能——一对一和一对多的方式详解

使用数据库:mysql
首先我们来看一下相关的代码实现:

<mapper namespace="com.lcb.mapping.userMapper"><!--association 一对一关联查询 --><select id="getClass" parameterType="int"resultMap="ClassesResultMap">select * from class c,teacher t where c.teacher_id=t.t_id andc.c_id=#{id}</select><resultMap type="com.lcb.user.Classes" id="ClassesResultMap"><!-- 实体类的字段名和数据表的字段名映射 --><id property="id" column="c_id"/><result property="name" column="c_name"/><association property="teacher"javaType="com.lcb.user.Teacher"><id property="id" column="t_id"/><result property="name" column="t_name"/></association></resultMap><!--collection 一对多关联查询 --><select id="getClass2" parameterType="int"resultMap="ClassesResultMap2">select * from class c,teacher t,student s where c.teacher_id=t.t_idand c.c_id=s.class_id and c.c_id=#{id}</select><resultMap type="com.lcb.user.Classes" id="ClassesResultMap2"><id property="id" column="c_id"/><result property="name" column="c_name"/><association property="teacher"javaType="com.lcb.user.Teacher"><id property="id" column="t_id"/><result property="name" column="t_name"/></association><collection property="student"ofType="com.lcb.user.Student"><id property="id" column="s_id"/><result property="name" column="s_name"/></collection></resultMap></mapper>

一对一:
有联合查询和嵌套查询,联合查询是几个表联合查询,只查询一次, 通过在
resultMap 里面配置 association 节点配置一对一的类就可以完成;
嵌套查询是先查一个表,根据这个表里面的结果的 外键 id,去再另外一个表里面查询数据,也是通过 association 配置,但另外一个表的查询通过 select 属性配置。

一对多:
有联合查询和嵌套查询。联合查询是几个表联合查询,只查询一次,通过在
resultMap 里面的 collection 节点配置一对多的类就可以完成;嵌套查询是先查一个表,根据这个表里面的 结果的外键 id,去再另外一个表里面查询数据,也是通过配置 collection,但另外一个表的查询通过 select 节点配置。

后续——MyBatis 的接口绑定以及实现方式