这个问题在使用mybatis的过程中会经常遇到。
一、连表查询
<select id="getStudent2" resultMap="StudentTeacher2">
SELECT s.`id` sid,s.`name` sname,t.`name` tname
FROM `student` s,`teacher` t
WHERE s.`tid`=t.`id`;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
各个属性介绍:
- id要保持一致,就是结果集的id和select的resultMap的值保持一致(使用结果集映射的只有select)
- result标签中的 property就是实体类的属性名,column就是SQL字段名
- association标签映射的是类变量,result标签映射的普通变量
- type 和 javatype都是实体类的名字
其实结果集映射学这些基本够了
二:嵌套查询
在SQL中设计多表查询的问题的时,有两种方式,一是多表连接,而是嵌套查询。其中多表连接常用,但是嵌套查询也应该了解
嵌套查询的结果集映射和上面有所不同
一个参数:
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher"
select="getTeacher"/>
</resultMap>
- association标签中的column为Student表的字段名,该字段将为select后面查询的参数。
- association标签中select属性中的查询的结果就是javatype的类型
注意:一个参数的时候,id=#{id}参数可以随意取值,多参数的时候,必须严格一致
多个参数:
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="{id=tid}" javaType="Teacher" select="getTeacher"/>
</resultMap>
association中column多参数配置:
column="{key=value,key=value}"
其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。加上{}即是多参数,须一致。
三、collection
collection标签和association标签使用方法差不多,不过对应的多对多确实需要花时间去理解