温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

MyBatis的动态SQL语句实现

发布时间:2020-08-24 20:30:30 来源:脚本之家 阅读:142 作者:weixin_45990046 栏目:编程语言

1. 动态SQL之<if>标签

我们根据实体类的不同取值,使用不同的SQL语句来进行查询。比如在id如果不为空时可以根据id查询,如果username不为空时还要加入用户名作为条件,这种情况在我们的多条件组合查询中经常会碰到。

<?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="com.joker.dao.IUserDao">
 
 <select id="findByUser" resultType="user" parameterType="user">
 select * from user where 1=1
 <if test="username!=null and username != '' ">
  and username like #{username}
 </if>
 <if test="address != null">
  and address like #{address}
 </if>
 </select>
</mapper>

注意:<if>标签的test属性中写的是对象的属性名,如果是包装类的对象要使用OGNL表达式的写法。另外要注意where 1=1的作用。

2. 动态SQL之<where>标签

为了简化上面where 1=1的条件拼装,我们可以采用<where>标签来简化开发。

<?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="com.joker.dao.IUserDao">
 
 <select id="findByUser" resultType="user" parameterType="user">
 select * from user
 <where>
  <if test="username!=null and username != '' ">
  and username like #{username}
  </if>
  <if test="address != null">
  and address like #{address}
  </if>
 </where>
 </select>
</mapper>

3. 动态SQL之<foreach>标签

<?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="com.joker.dao.IUserDao">
 
 <!-- 查询所有用户在 id的集合之中 
 foreach标签:用于遍历集合
  * collection:代表要遍历的集合元素,注意编写时不要写 #{}
  * open:代表语句的开始部分
  * close:代表结束部分
  * item:代表遍历集合的每个元素,生成的变量名
  * sperator:代表分隔符
 -->
 <select id="findInIds" resultType="user" parameterType="queryvo">
 select * from user
 <where>
  <if test="ids != null and ids.size() > 0">
  <foreach collection="ids" open="id in ( " close=")" item="uid" separator=",">
   #{uid}
  </foreach>
  </if>
 </where>
 </select>
</mapper>

4. MyBatis中的SQL片段

MyBatis的sql中可将重复的sql提取出来,使用时用include引用即可,最终达到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="com.joker.dao.IUserDao">
 
 <!-- 抽取重复的语句代码片段 -->
 <sql id="defaultSql">
 select * from user
 </sql>

 <select id="findAll" resultType="user">
 <include refid="defaultSql"></include>
 </select>
 
 <select id="findById" resultType="User" parameterType="int">
 <include refid="defaultSql"></include>
 where id = #{uid}
 </select>

</mapper>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI