<update id="batchUpdate" parameterType="java.util.List">
<foreach close="" collection="list" index="index" item="item" open="" separator=";">
update user set name=#{item.name,jdbcType=VARCHAR},age=#{item.age,jdbcType=INTEGER}
where id=#{item.id,jdbcType=INTEGER}
</foreach>
</update>
(3)批量删除
<delete id="batchDelete" parameterType="java.util.List">
<foreach close="" collection="list" index="index" item="item" open="" separator=";">
delete from user
where id=#{item.id,jdbcType=INTEGER}
</foreach>
</delete>
二、模糊查询
<select id="selectLikeName" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where name like CONCAT('%',#{name},'%' )
</select>
上面的模糊查询语句是Mysql数据库的写法示例,用到了Mysql的字符串拼接函数CONCAT,其它数据库使用相应的函数即可。
三、多条件查询
多条件查询常用到Mybatis的if判断,这样只有条件满足时,才生成对应的SQL。
<select id="selectUser" parameterType="map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
<where>
<if test="name != null">
name = #{name,jdbcType=VARCHAR}
</if>
<if test="age != null">
and age = #{age,jdbcType=INTEGER}
</if>
</where>
</select>
四、联表查询
联表查询在返回结果集为多张表的数据时,可以通过继承resultMap,简化写法。例如下面的示例,结果集在User表字段的基础上添加了Dept的部门名称。
<resultMap id="ExtResultMap" type="com.research.mybatis.generator.model.UserExt" extends="BaseResultMap">
<result column="name" jdbcType="VARCHAR" property="deptName" />
</resultMap>
<select id="selectUserExt" parameterType="map" resultMap="ExtResultMap">
select
u.*, d.name
from user u inner join dept d on u.dept_code = d.code
<where>
<if test="name != null">
u.name = #{name,jdbcType=VARCHAR}
</if>
<if test="age != null">
and u.age = #{age,jdbcType=INTEGER}
</if>
</where>
</select>
上述示例皆在MySql数据库下测试通过,这里限于篇幅,相应的代码及测试类我就不贴上来了。完整的代码及测试类,可以查看我的Github项目地址:https://github.com/wdmcygah/research-mybatis。主要是UserService和UserServiceTest两个类,仓库里面还有些与本博文不相关的代码,注意区分。