您的位置:首页 > 数据库

MyBatis入门【六】动态SQL

2018-01-30 01:11 330 查看
在MyBatis中,运用动态SQL可以进行动态的添加操作数据库的条件,使操作数据库更加灵活

代码示例

<!-- where可以自动去掉条件中的第一个and -->
<select id="findUserList" parameterType="UserQueryVo全路径/别名" resultMap="UserCustom全路径">
SELECT * FROM USER
<where>
<if test="userCustom != null">
<if test="userCustom.sex != null and userCustom.sex != ' ' ">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username != null and userCustom.username != ' ' ">
and user.username LIKE '%${userCustom.username}%'
</if>
</if>
</where>
</select>


SQL片段

将动态SQL代码抽取出来形成SQL片段,其他statement就可以调用定义SQL片段,

id:SQL片段唯一标识

经验:

1、基于单表来定义SQL片段,SQL片段可重用性高

2、在SQL片段中不要包含where

<sql id="query_user_where">
<if test="userCustom != null">
<if test="userCustom.sex != null and userCustom.sex != ' ' ">
and user.sex = #{userCustom.sex}
</if>
<if test="userCustom.username != null and userCustom.username != ' ' ">
and user.username LIKE '%${userCustom.username}%'
</if>
</if>
</sql>


引用SQL片段

<select id="findUserList" parameterType="UserQueryVo全路径/别名" resultMap="UserCustom全路径">
SELECT * FROM USER
<where>
<!-- 引用SQL片段 id,如果不在本mapper文件中,需要前边添加namespace -->
<include refid="query_user_where"></include>
<!-- 在这里还可引用其他SQL片段 -->
</where>
</select>


foreach

向SQL中传递数组或List,mybatis使用foreach解析

1、select * from user where id=1 or id=10 or id=123

包装类的定义

public class UserQueryVo{
//传入多个id
private List<Integer> ids;
//在此处应生成setget
}


mapper.xml文件中SQL片段:

<!-- 使用foreach遍历ids
collection:指定输入对象中集合属性
item:每个遍历生成对象串
open:开始遍历时拼接的串
close:结束遍历时拼接的串
separator:遍历的两个对象中需要拼接的串
-->
<foreach collection="ids" item="user_id" open="AND (" close=")" separator="or">
<!-- 每个遍历需要拼接的串-->
id=#{user_id}
</foreach>


效果串: AND (id=1 or id=10 or id=123)

2、select * from user where id in (1,10,123)

<foreach collection="ids" item="user_id" open="AND id IN (" close=")" separator=",">
<!--每个遍历需要拼接的串-->
i#{user_id}
</foreach>


效果串: AND id IN(1 ,10, 23)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: