SQL片段的定义
将公用的SQL片段提取出来减少工作量
<sql id="studentColumns">
stu_id,stu_Age,stu_Sex,stu_Name
</sql>
<select id="queryStudentInfo" resultType="student" parameterType="map">
select <include refid="studentColumns"></include>
from student_info where stu_id = #{id}
</select>
也可以在sql片段中定义形参
<sql id="studentColumns">
${prefix}.stu_id,${prefix}.stu_Age,${prefix}.stu_Sex,${prefix}.stu_Name
</sql>
<select id="queryStudentInfo" resultMap="studentMap" parameterType="int">
select
<include refid="studentColumns">
<property name="prefix" value="m"/>
</include>
from student_info m where m.stu_id = #{id}
</select>
因为我们注入的参数并不是SQL语句的参数而是SQL语句本身,前面有说过#{}用来注入参数,${}注入sql语句本身
resultMap结果集定义详解
* resultMap里面的元素
<resultMap type="" id="">
<constructor></constructor>
<id/>
<result/>
<association property=""></association>
<collection property=""></collection>
<discriminator javaType=""></discriminator>
</resultMap>
type: 结果集的type,一般都是定义为javaBean,定义为map,不方便
constructor:在javabean没有创建无参的构造器时候,指定的调用的构造器方法
id和result:指定映射关系
<!--
column: 映射的列名
property: 映射的JavaBean的属性
jdbctype: 数据库里面的类型
javaType: java里面的类型
typeHandler: 类型转换中,指定的处理器,可以不指定
-->
<result column="stu_age" property="stuAge" jdbcType="varchar" javaType="string"
typeHandler="类型处理器"
/>
级联查询的处理
association: 表示一对一关系
collection: 表示一对多关系
discriminator: 根据条件选择结果集
一对一级联查询
* 学生和学生卡是一对一关系
需求是查询学生的时候将学生卡信息也一并查询出来
* student对象中定义了StudentCard对象
public class Student {
private Integer stuId;
private Integer stuAge;
private String stuSex;
private String stuName;
private StudentCard card;
//get/set .....
public class StudentCard {
private Integer stuId;
private Integer cardNum;
private Date registerTime;
//get/set....
定义studentMapper.xml
<resultMap type="student" id="studentAndCourse">
<id column="stu_id" property="stuId"/>
<result column="stu_age" property="stuAge" />
<result column="stu_sex" property="stuSex" />
<result column="stu_name" property="stuName"/>
<association property="card" column="stu_id"
select="cn.bing.mapper.StudentCardMapper.queryStudentCardInfo">
</association>
</resultMap>
<select id="queryStudentInfo" resultMap="studentAndCourse" parameterType="int">
select * from student_info m where m.stu_id = #{id}
</select>
在association元素中
card是关联对象的字段名称,select是调用的另一个CardMapper里的查询方法,必须写全路径+方法名称
column是方法形参获取的值对应在Student的列名(此时是student中Bean的主键列名)
* StudentCardMapper.xml
<mapper namespace="cn.bing.mapper.StudentCardMapper">
<resultMap type="studentCard" id="cardInfoMapp