Mybatis学习(十二)mybatis理解动态sql及sql片段

在上面的文章的基础上我们做一下动态sql和sql片段

需求分析:

sql片段理解

详细设计:

代码实现

在User.xml做出修改

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 <mapper namespace="cn.bj.mybatis.model.IUserOperation">
 <select id="findUserList" parameterType="cn.bj.mybatis.model.UserQueryVO"
 	resultType="cn.bj.mybatis.model.UserCustom">
 	select * from t_user
 	<!-- where可以自动去掉第一个条件的and -->
 	<where>
 		<if test="userCustom!=null">
 			<if test="userCustom.sex!=null and userCustom.sex!=''">
 				and t_user.sex=#{userCustom.sex}
 			</if>
 			<if test="userCustom.username!=null and userCustom.username!=''">
 				and t_user.username like '%${userCustom.username}%'
 			</if>
 		</if>
 	</where>
 </select>
</mapper>
测试类还是上一章的那个Mybatistest,java

sql片段

sql片段的意思就是将sql的部分语句单独定义出来。然后在使用的时候引入。

修改User.xml看看什么是sql片段,和上面的文件进行比较。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

 <mapper namespace="cn.bj.mybatis.model.IUserOperation">
 <select id="findUserList" parameterType="cn.bj.mybatis.model.UserQueryVO"
 	resultType="cn.bj.mybatis.model.UserCustom">
 	select * from t_user
 	<!-- where可以自动去掉第一个条件的and -->
 	<where>
 		<!-- sql片段引入 -->
 		<include refid="query_user_where"></include>
 	</where>
 </select>
 <!-- sql片段 -->
 <sql id="query_user_where">
 	<if test="userCustom!=null">
 			<if test="userCustom.sex!=null and userCustom.sex!=''">
 				and t_user.sex=#{userCustom.sex}
 			</if>
 			<if test="userCustom.username!=null and userCustom.username!=''">
 				and t_user.username like '%${userCustom.username}%'
 			</if>
 		</if>
 </sql>
</mapper>

看着两段代码就知道如何运用sql片段。

怎么实现 OR呢?

比如 where id=1 or id=3 or id=6

<if test="ids!=null">
 			<foreach collection="ids" item="userid" open=" and (" close=")" separator="or">
 				<!-- 遍历拼接的串 -->
 				id=#{id}
 			</foreach>
 </if>

比如 where id in(1,3,6)

<if test="ids!=null">
 			<foreach collection="ids" item="userid" open=" and id in (" close=")" separator=",">
 				<!-- 遍历拼接的串 -->
 				#{id}
 			</foreach>
 </if>





  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值