Mybatis动态SQL实现
Mybatis提供了动态SQL,也就是可以根据用户提供的参数,动态决定查询语句依赖的查询条件或SQL语句的内容
动态SQL标签
- if和where
这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
<!--动态Sql : where / if--> <select id="selectAll" resultType="com.whz.pojo.User"> select <include refid="all"/> from users <where> <if test="id != null and id != 0"> AND id = #{id} </if> <if test="name != null and name != ''"> AND name = #{name} </if> <if test="money!= null and money != ''"> AND money= #{money} </if> </where> </select>
- choose、when、otherwise 标签(类似于 Java 中的 switch、case、default)
有三个条件,id,username,sex,只能选择一个作为查询条件
如果 id 不为空,那么查询语句为:select * from user where id=?
如果 id 为空,那么看username 是否为空,如果不为空,那么语
句为 select * from user where username=?;
如果 username 为空,那么查询语句为 select * from user where
sex=?<!--动态Sql: choose、when、otherwise 标签--> <select id="selectAll2" resultType="com.whz.pojo.User"> select * from users <where> <choose> <when test="name != null and name != ''"> AND name = #{name} </when> <when test="money != null and money!= ''"> AND money= #{money} </when> <otherwise> AND id = #{id} </otherwise> </choose> </where> </select>
- set 标签(if+set)
如果第一个条件 username 为空,那么 sql 语句为:update user u set u.sex=? where id=?
如果第一个条件不为空,那么 sql 语句为:update user u set u.username = ? ,u.sex = ? where id=?<!--动态Sql: set 标签--> <update id="updateSet" parameterType="com.whz.pojo.User"> update users <set> <if test="name != null and name != ''"> name = #{name}, </if> <if test="money!= null and money!= ''"> money= #{money}, </if> </set> where id = #{id} </update>
- foreach标签
select * from user where id=1 or id=2 or id=3
<select id="selectUserByListId" parameterType="com.whz.pojo.User" >resultType="com.whz.pojo.User"> select * from user <where> <!-- collection:指定输入对象中的集合属性 item:每次遍历生成的对象 open:开始遍历时的拼接字符串 close:结束时拼接的字符串 separator:遍历对象之间需要拼接的字符串 select * from user where 1=1 and (id=1 or id=2 or id=3) --> <foreach collection="ids" item="id" open="and (" close=")" >separator="or"> id=#{id} </foreach> </where> </select>
select * from user where id in (1,2,3)
<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" >resultType="com.ys.po.User"> select * from user <where> <!-- collection:指定输入对象中的集合属性 item:每次遍历生成的对象 open:开始遍历时的拼接字符串 close:结束时拼接的字符串 separator:遍历对象之间需要拼接的字符串 select * from user where 1=1 and id in (1,2,3) --> <foreach collection="ids" item="id" open="and id in (" close=") " >separator=","> #{id} </foreach> </where> </select>
Mybatis的分页
方法一:
UserMapper.java(interface)
userMapper.xml
Test.java
方法二:
UserMapp.java(interface)
UserMapper.xml
Test.java
方法三:
UserMapper.java(interface)
UserMapper.xml
Test.java