mapper.xml文件详解

1:namespace:不能重复的命名空间
2:select:sql语句映射
3:select>id sql语句的独有id
4:select>parmeterType sql语句传入的参数类型
5:select>resultType sql语句返回的参数类型
6:select>resultMap sql语句中的列名与bean中名称不一致时 可以使用resultMap进行定义或者在列名前定义别名

  • select>resultMap=resultMap的id
  • resultMap type的值等于数据库中表对于的bean类
  • resultMap>id定义主键 id>property=你封装的bean中的列名 id>columu是你数据库中表的列名
  • resultMap>result定义非主键
  • resultMap>association(关联) 用于1对1 需要关联的表 property=对应的javabean中的属性 column对应的数据库表中的列名 javaType=关联的javabean返回类型 select 等于嵌套的select语句id
  • resultMap>collection(集合) 用于1对多 property=对应的javabean中的属性 column对应的数据库表中的列名 javaType=关联的javabean返回类型
1
2
3
4
5
6
7
<resultMap type="orders" id="orderResultMap">
<!-- id属性定义主键 -->
<id property="id" column="order_id" />
<!-- result属性定义非主键 -->
<result property="orderNo" column="order_no" />
<result property="price" column="order_price" />
</resultMap>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis.mapping.class2Mapper">
<!-- 方式一: 嵌套结果: 使用嵌套结果映射来处理重复的联合结果的子集
SELECT * FROM class c, teacher t,student s WHERE c.teacher_id=t.t_id AND c.C_id=s.class_id AND c.c_id=1 -->
<select id="getClassId" parameterType="int"
resultMap="ClassIdResultMap">
select * from class,teacher,student where
class.c_id=student.class_id and
class.teacher_id=teacher.t_id and
c_id=#{id};
</select>
<resultMap type="Classes" id="ClassIdResultMap">
<id property="id" column="c_id" />
<result property="name" column="c_name" />
<association property="teacher" javaType="Teacher"
column="teacher_id">
<id property="id" column="t_id" />
<result property="name" column="t_name" />
</association>
<collection property="students" ofType="Student">
<id property="id" column="s_id" />
<result property="name" column="s_name" />
</collection>
</resultMap>
<!-- 方式二:嵌套查询:通过执行另外一个SQL映射语句来返回预期的复杂类型 SELECT * FROM class WHERE c_id=1;
SELECT * FROM teacher WHERE t_id=1 //1 是上一个查询得到的teacher_id的值 SELECT * FROM
student WHERE class_id=1 //1是第一个查询得到的c_id字段的值 -->
<select id="getClassById2" parameterType="int"
resultMap="getClassById2ResultsetMap">
select * from class where c_id=#{id}
</select>
<resultMap type="Classes" id="getClassById2ResultsetMap">
<id property="id" column="c_id" />
<result property="name" column="c_name" />
<association property="teacher" column="teacher_id"
javaType="Teacher" select="getTeacher2"></association>
<collection property="students" ofType="Student"
column="c_id" select="getStudents"></collection>

</resultMap>
<select id="getTeacher2" parameterType="int"
resultType="Teacher">
select t_id id,t_name name from teacher where t_id=#{id}
</select>
<select id="getStudents" parameterType="int"
resultType="Student">
select s_id id,s_name name from student where class_id=#{id}
</select>
</mapper>