上一篇博客中已经总结了Mybatis的基本的总的配置文件和映射文件的配置,已经实现了最基本的增删改查的功能。这篇博客就来总结以下在使用Mybatis框架的过程中常用的配置参数。
(1)配置结果映射集
Mybatis是是持久层数据库,它最终是要去操作数据库。所有当我们在配置文件中写了操作数据库的语句,当它执行的时候必定会有一个返回结果,增,删,改的返回值是一个整形,我们可以省略。当我们查询数据库的时候,返回的是一个实列对象或者是类的一些属性,所以我们必须要接受这个值然后返回给方法调用者。这时候就要我们进行映射集的配置了。
这是我们之前的写法,因为我们要查的是学生,返回的时学生对象,所以我们的:resultType="com.pojo.StudentPojo"就指明我们返回的类型是学生对象。但是,如果当我们的sql语句和pojo学生类的属性不对应的时候,我们就要配置一个映射关系。
<select id="SelectALlStudent" resultType="com.pojo.StudentPojo">
select sid,name,chinese,math,rank from student
</select>
当我将代码中的sid改为id的时候,就会报下面的一个错误。
Mapped Statements collection does not contain value for com.dao.StudentDao.SelectAllStudent
我们进行如下配置:
<!--type是我们指定的实体类,id是我们给这个结果集的一个名字-->
<resultMap type="com.pojo.StudentPojo" id="stuMapper">
<!--id属性映射主键字段-->
<id column="sid" property="sid"/>
<!--result属性映射非主键关系-->
<result column="name" property="NAME"/>
<result column="math" property="math"/>
<result column="chinese" property="chinese"/>
<result column="rank" property="rank"/>
</resultMap>
然后在查询语句中做如下配置
<select id="SelectStudentByName" resultMap="stuMapper" parameterType="String">
select id,name,chinese,math,rank from student where name=#{value}
</select>
代码中我们的返回结果已经变成了我们配的写的那个结果集映射,意思就是当我们sql语句将这个学生查出来之后按照配的映射关系进行填充。然后返回给调用者。
(二)多主键查询
<!--多主键查询,当我们查询操作的时候,可以传多个参数进来,比如传两个学生学号,就会返回两个学生对象-->
<select id="MultiKeyQuery" parameterType="list" resultMap="stuMapper">
select sid,name,chinese,math from student
<where>
<choose>
<when test="list==null or list.size()==0">
1=2
</when>
<otherwise>
sid in
<foreach collection="list" open="(" close=")" separator="," item="i">
#{i}
</foreach>
</otherwise>
</choose>
</where>
</select>
这个我没传参数运行之后打印的sql语句
这个我传了两个学号之后打印的sql语句
传参时是将参数放在一个数组中
<choose>
<when test="list==null or list.size()==0">
1=2
</when>
<otherwise>
sid in
<foreach
collection="list" open="(" close=")" separator="," item="i">
#{i}
</foreach>
</otherwise>
</choose>
然后这段代码是进行判断,如果集合为空,那么1=2恒不成立,也就是后面的条件不存在,所以没有数据。当我传了两个参数时,foreach循环遍历集合,将参数取出来,然后进行查询。
(3)多条件查询
<!--多条件查询-->
<select id="MultiQuery" resultMap="stuMapper">
select sid,name,chinese,chinese,math,rank from student
<where>
<if test="sid!=null">
sid=#{sid}
</if>
<if test="NAME!=null">
and name like concat(#{name}`%`)
</if>
</where>
</select>