通过接口绑定解决多参数的传递
1 方式一
a) 接口中定义方法
User selByUP(String username, String password);
b) 映射文件中提供对应的标签. 此时, SQL 语句中获取方式有两种, 通过
#{index}
或
#{param+数字}
的方式.不能通过username password来取,因为配置文件识别不到
<select id="selByUP" resultType="user">
select * from t_user where username=#{0} and password=#{1}
</select>
2
方式二
a) 接口中定义方法, 参数中使用
@Param
注解设定参数名用于在 SQL 语句中使用.
User selByUP(@Param("username") String username, @Param("password") String password);
b) 映射文件中提供对应的标签. 此时, SQL 语句中获取方式有两种, 通过
#{参数名称}
或
#{param+数字}
的方式.不能通过索引,因为封装成为了一个map对象,没有0和1
<select id="selByUP" resultType="user">
select * from t_user where username=#{username} and password=#{password}
</select>
动态 SQL
根据条件的不同, SQL 语句也会随之动态的改变. MyBatis中, 提供了一组标签用于实现动态 SQL.
1 <if>
用于进行条件判断, test 属性用于指定判断条件. 为了拼接条件, 在 SQL 语句后强行添加 1=1 的恒成立条件.
<select id="sel" resultType="user">
select * from t_user where 1=1
<if test="username != null and username != ''">
and username=#{username}
</if>
<if test="password != null and password != ''">
and password=#{password}
</if>
</select>
2 <where>
用于管理 where 子句. 有如下功能:
a)如果没有条件, 不会生成 where 关键字
b)如果有条件, 会自动添加 where 关键字
c)如果第一个条件中有 and, 去除之
<select id="sel" resultType="user">
select * from t_user
<where>
<if test="username != null and username != ''">
and username=#{username}
</if>
<if test="password != null and password != ''">
and password=#{password}
</if>
</where>
</select>
3 <choose><when><otherwise>
这是一套标签, 功能类似于 switch...case...
<select id="sel" resultType="user">
select * from t_user
<where>
<choose>
<when test="username != null and username != ''">
and username = #{username}
</when>
<when test="password != null and password != ''">
and password = #{password}
</when>
<otherwise>
and 1=1
</otherwise>
</choose>
</where>
</select>
4 <set>
用于维护 update 语句中的 set 子句. 功能如下:
a)满足条件时, 会自动添加 set 关键字
b)会去除 set 子句中多余的逗号
c)不满足条件时, 不会生成 set 关键字
int updUser(User user);
<update id="updUser" parameterType="user">
update t_user
<set>
id=#{id},
<!-- 防止所有条件不成立时的语法错误 -->
<if test="username != null and username != ''">
username=#{username},
</if>
<if test="password != null and password != ''">
password=#{password},
</if>
</set>
where id=#{id}
</update>
5 <trim>
用于在前后添加或删除一些内容
a)prefix, 在前面添加内容
b)prefixOverrides, 从前面去除内容
c)suffix, 向后面添加内容
d)suffixOverrides, 从后面去除内容
<update id="updUser" parameterType="user">
update t_user
<!--
prefix: 前缀, 表示向前面添加内容
prefixOverrides: 从前面删除内容
suffix: 后缀, 表示向后面添加内容
suffixOverrides: 从后面删除内容
-->
<trim prefix="set" prefixOverrides="user" suffix="hahaha" suffixOverrides=",">
username=#{username},
</trim>
where id=#{id}
</update>
6 <bind>
用于对数据进行再加工, 用于模糊查询
<select id="sel" resultType="user">
select * from t_user
<where>
<if test="