一、一对一关联查询
resultMap标签:手动封装映射规则的标签。查询的结果放在resultTypeh中指定的实体类。
编写自定义映射的结果集。就需要resultMap完成。
<resultMap id="" type="">
<association property="" javatype="">
</association>
</resultMap>
id表示当前自定义映射规则需要取一个名称,使用id来命名
type:表示Mybatis关联查询中主表的完整包结构名称。
association:表示一对一关联查询从表的配置
properties:表示主表中哪个字段是从表一对一映射的关键字段
javatype:表示从表映射的实体类型
二、一对多关联查询
与一对一类似,只不过是从表关系标签变为<Collection>
<resultMap id="deptResultMap" type="com.pl.pojo.Dept" autoMapping="true">
<result column="did" property="did"/>
<collection property="empList" ofType="com.pl.pojo.emp">
<id property="eid" column="eid"/>
<result column="emp_no" property="empNo"/>
<result column="emp_name" property="empName"/>
<result column="job" property="job"/>
<result column="line_manager" property="lineManager"/>
<result column="Hire_date" property="HireDate"/>
<result column="salary" property="salary"/>
<result column="bonus" property="bonus"/>
<result column="dept_no" property="deptNo"/>
</collection>
</resultMap>
<select id="findDeptAll" resultMap="deptResultMap">
select d.dept_name,e.*
from t_dept d left join t_emp e
on d.dept_no = e.dept_no
</select>
三、多对多关联查询
老师与学生存在多对多关系,在规定映射关系的resultMap中,拆解成在老师中的一对多和在学生类中的一对多,所以从表关键词和上面Collection写法一样
<resultMap id="teacherResultMap" type="com.pl.pojo.Teacher" autoMapping="true">
<id column="tid" property="tid"/>
<collection property="stuList" ofType="com.pl.pojo.Student" javaType="java.util.List">
<id column="sid" property="sid"/>
<result column="student_name" property="studentName"/>
<result column="student_gender" property="studentGender"/>
<result column="student_age" property="studentAge"/>
</collection>
</resultMap>
<select id="findAllTeacher" resultMap="teacherResultMap">
select tt.*,s.student_name from
(select t.* ,ts.sid from t_teacher t left join ts_relation ts on t.tid = ts.tid) tt
left join student s on s.sid = tt.sid
</select>
四、驼峰映射规则
在数据库中表的字段名称多个单词都是小写,单词与单词之间下划线连接。在声明java
与之表对应的实体类时,要求去掉下划线,然后将第二个单词开始首字母大写。
1.resultMap标签:用来自定义映射规则。
语法分析:在进行一对一查询的时候,主表中需要编写大量的result标签声明,语法过于繁杂。
解决方案:Mybatis提供了一个功能,称之为驼峰映射。在核心配置文件开启驼峰映射
(默认驼峰映射是关闭的)
在Mybatis-config中添加Sittings标签:
注意在主表映射关系中要保留id的映射:
<resultMap id="UserResultMap" type="com.pl.pojo.User" autoMapping="true">
<id column="uid" property="uid"/>
字表中的一个都不能省略:
<association property="address" javaType="com.pl.pojo.Address">
<id column="aid" property="aid"/>
<id column="uid" property="uid"/>
<result column="province_name" property="provinceName"/>
<result column="city_name" property="cityName"/>
<result column="area_name" property="areaName"/>
<result column="address" property="address"/>
<result column="created_user" property="createdUser"/>
<result column="created_time" property="createdTime"/>
<result column="modified_user" property="modifiedUser"/>
<result column="modified_time" property="modifiedTime"/>
</association>