您的位置:首页 > 数据库

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

2015-06-11 11:14 555 查看
在上面的文章的基础上我们做一下动态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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: