resultMap手动映射
当数据库表中的字段名称与pojo的实体类的名称不同的时候,使用resultMap:
示例代码:
<mapper namespace="com.zrxjuly.mybatis.mapper.OrderMapper">
<!-- type:为实体类的类名
id的值要与写的sql语句中resultMap的值一致.
colume:数据库中表的字段名称
property:实体类中属性的名称
-->
<resultMap type="Orders" id="orders">
<result column="user_id" property="userId"/>
</resultMap>
<!-- resultMap的值要与resultMap标签中的id的值一致 -->
<select id="selectOrder" resultMap="orders">
select * from orders
</select>
</mapper>
动态sql
通过MyBatis提供的各种标签方法实现动态拼接sql。
if标签
示例代码:
<select id="selectUserBySexAndUsername" parameterType="User" resultType="User">
select * from user
where 1=1
<if test="sex != null and sex != ''">
sex=#{sex}
</if>
<if test="username != null and username != ''">
and username=#{username}
</if>
</select>
注:where后的1=1的含义:如果sex为空的话,则语句就会变成select * from user where and username=#{username}
,这样就会报sql语法错误。1=1意思是true
where标签
不用where 1=1的方法,直接用where标签:
<select id="selectUserBySexAndUsername" parameterType="User" resultType="User">
select * from user
<!-- where可以去掉第一个前and,也就是说在加and语句的时候要把and放在条件之前 -->
<where>
<if test="sex != null and sex != ''">
sex=#{sex}
</if>
<if test="username != null and username != ''">
and username=#{username}
</if>
</where>
</select>
sql片段
若sql语句中多次出现重复部分,可以提取出来公用:
<!-- 提取出来的sql片段,公共部分, -->
<sql id="selectA">
select * from user
</sql>
<select id="selectUserBySexAndUsername" parameterType="User" resultType="User">
<include refid="selectA" /><!-- 此处引用了select * from user -->
<!-- where可以去掉第一个前and,也就是说在加and语句的时候要把and放在条件之前 -->
<where>
<if test="sex != null and sex != ''">
sex=#{sex}
</if>
<if test="username != null and username != ''">
and username=#{username}
</if>
</where>
</select>
foreach标签
当要求根据多个参数进行查询时,用foreach循环遍历多个值:
<!-- collection:传入的参数的名称,
例如:如果接口传过来的参数为Integer[]类型的,则collection="array",此时parameterType属性去掉
如果接口传过来的参数为List<Integer>类型的,则collection="list",此时parameterType属性去掉
item:循环遍历的值
open:遍历开始
close:遍历结束
separator:分隔符
该sql语句相当于:select * from user where id in(1,2,3)
-->
<select id="selectUserByIds" parameterType="QueryVo" resultType="User">
select * from user
<where>
id in
<foreach collection="idList" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</where>
</select>
参数为Integer[]类型:
<select id="selectUserInteger" resultType="User">
select * from user
<where>
id in
<foreach collection="array" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</where>
</select>
参数为List<Integer>
类型:
<select id="selectUserList" resultType="User">
select * from user
<where>
id in
<foreach collection="list" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</where>
</select>
参数为类集合:List<User>
<!-- 批量删除用户
当传入的参数类型为List<类名>这样的集合时,parameterType的值为类名,
foreach标签中collection的值为list,item的值为传入的参数名称(delete("User.deleteBatch", userList);),
循环遍历的值的获取要用item值.属性名。
-->
<delete id="deleteBatch" parameterType="User">
DELETE FROM userinfo
WHERE id IN
<foreach collection="list" item="userList" open="(" close=")" separator=",">
#{userList.id}
</foreach>
</delete>