mybatis核心:
对sql语句进行灵活操作,通过表达式判断,对sql进行灵活拼接,组装
对查询条件进行判断,如果查询条件不为空,才进行拼接
if && where
<!--用户信息的综合查询-->
<!--#{userCustom.sex}取出包装类型中性别值-->
<!--${userCustom.username}取出包装类型中姓名值-->
<!--<select id="findUserList" parameterType="com.sws.entity.UserQueryVo" resultType="com.sws.entity.UserCustom">-->
<!--select * from user where user.sex=#{userCustom.sex} and user.username like '%${userCustom.username}%'-->
<!--</select>-->
<select id="findUserList" parameterType="com.sws.entity.UserQueryVo" resultType="com.sws.entity.UserCustom">
select * from user
<where>
<if test="userCustom.sex != null">
and user.sex = #{userCustomer.sex}
</if>
<if test="user.username != null">
and user.username like '%${userCustom.username}%'
</if>
</where>
</select>
sql片段
<!--定义sql片段
id:唯一标识
基于单表来定义sql片段,可重用性才高
在sql片段中不要包括where-->
<sql id="query_user_where">
<if test="userCustom.sex != null">
and user.sex = #{userCustomer.sex}
</if>
<if test="user.username != null">
and user.username like '%${userCustom.username}%'
</if>
</sql>
<!--使用sql片段id,如果refid指定id不在本mapper中,需要添加namespace-->
<select id="findUserList" parameterType="com.sws.entity.UserQueryVo" resultType="com.sws.entity.UserCustom">
select * from user
<where>
<include refid="query_user_where"></include>
</where>
</select>
foreach
在用户查询列表和查询总数的statement中增加多个id查询
--sql语句
select * from user where id = 1 or id=10 or id=15;
select * form user where id in (1,10,16)
在输入参数类型中添加List<Integer> ids多个id
//包装对象
public class UserQueryVo {
//包装所需要的查询条件
//用户查询体条件
//多个id
private List<Integer> ids;
private UserCustom userCustom;
public UserCustom getUserCustom() {
return userCustom;
}
public void setUserCustom(UserCustom userCustom) {
this.userCustom = userCustom;
}
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
//可以包装其他的查询条件,订单、商品
}
<sql id="query_user_where">
<if test="userCustom.sex != null">
and user.sex = #{userCustomer.sex}
</if>
<if test="user.username != null">
and user.username like '%${userCustom.username}%'
</if>
<if test="ids != null">
<!-- 使用foreach遍历ids-->
<!--collection:指定输入对象的集合属性-->
<!--item:每次遍历生成的对象名-->
<!--open:开始遍历时拼接字符串-->
<!--close:结束遍历需要拼接的字符串-->
<!--separator:遍历过程所需要拼接的字符串-->
<!--目标:and ( id=1 or id=10 or id=15)-->
<foreach collection="ids" item="id" open="and (" close=")" separator=" or ">
<!--每次遍历所需要拼接的字符串-->
id = #{id}
</foreach>
</if>
</sql>
<!--目标:and id in (1,10,15)-->
<foreach collection="ids" item="id" open="and id in (" close=")" separator=" ,">
<!--每次遍历所需要拼接的字符串-->
#{id}
</foreach>

本文介绍 MyBatis 中 SQL 的动态拼接方法,包括 if 和 where 标签的使用,以及如何利用 foreach 实现 in 条件的动态拼接,通过具体的示例代码展示了如何构造灵活且可重用的 SQL 查询。

被折叠的 条评论
为什么被折叠?



