本篇文章给大家分享的是有关如何在MyBatis中实现动态SQL,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
if 元素
if元素条件判断,动态 SQL 最常做的事就是有条件地包括 where 子句。例如:
<select id=”findActiveBlogWithTitleLike” parameterType=”Blog” resultType=”Blog”>
SELECT * FROM BLOG WHERE state = ‘ACTIVE'
<if test=”title != null”>
AND title like #{title}
</if>
</select>
where元素
where元素知道插入“where”如果它包含的标签中有内容返回的话。此外,如果返回的内容 以“AND” 或者 “OR”开头,它会把“AND” 或者 “OR”去掉。
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
select * from t_student
<where>
<if test="name!=null">
and name=#{name}
</if>
<if test="age!=null">
and age=#{age}
</if>
</where>
</select>
choose元素
有时候我们不想应用所有的条件,而是想从多个选项中选择一个。与 java 中的 switch 语句 相似,MyBatis 提供了一个 choose 元素。
when元素
当when里面的条件成立时,执行when标签内的语句
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
select * from t_student
<where>
<choose>
<when test="name!=null">
and name=#{name}
</when>
<when test="age!=null">
and age=#{age}
</when>
</choose>
</where>
</select>
otherwise元素
当所有when都不成立了,执行otherwise
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
select * from t_student
<where>
<choose>
<when test="name!=null">
and name=#{name}
</when>
<when test="age!=null">
and age=#{age}
</when>
<otherwise>
and name='jim'
</otherwise>
</choose>
</where>
</select>
trim元素
如果 where 元素的行为并没有完全按您想象的那样,您还可以使用 trim 元素来自定义。
trim内的if有成立的就添加一个前缀用prefix=""定义,没有就不添加。
trim元素也可以去掉where后面指定的关键字and或者or等等,用prefixOverrides=""定义
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
select * from t_student
<trim prefix="where" prefixOverrides="and">
<if test="name!=null">
and name=#{name}
</if>
<if test="age!=null">
and age=#{age}
</if>
</trim>
</select>
set元素
在动态update语句里相似的解决方式叫做set,这个set元素能够动态地更新列。
set 元素将动态的配置set关键字,也用来剔除追加到条件末尾的任何不相关的逗号。
<update id="updateStudent" parameterType="Student">
update t_student
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="age!=null">
age=#{age},
</if>
</set>
where id=#{id}
</update>
当然了,聪明的你肯定想知道等同的 trim 元素该怎么写吧,它就像这样 :
<update id="updateStudent" parameterType="Student">
update t_student
<trim prefix="set" prefixOverrides=",">
<if test="name!=null">
name=#{name},
</if>
<if test="age!=null">
age=#{age},
</if>
</trim>
where id=#{id}
</update>
注意这种情况,我们剔除了一个后缀, 同时追加了一个前缀 。
Foreach 元素
另一个动态 SQL 经常使用到的功能是集合迭代,通常用在 in条件句
foreach 元素非常强大,允许您指定一个集合,申明能够用在元素体内的项和索引变量。也 允许您指定开始和结束的字符,也可以加入一个分隔符到迭代器之间。这个元素的聪明之处在于 它不会意外地追加额外的分隔符。
<select id="findStudentByAge" resultMap="studentInfo">
select * from t_student where age in
<foreach collection="list" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
测试方法如下:
public void findStudentByAge() {
SqlSession sqlSession = null;
try {
sqlSession = MyBatisUtil.getsqlSession();
StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
List<Integer> list= new ArrayList<Integer>();
list.add(21);
list.add(23);
List<Student> liststudent =studentDao.findStudentByAge(list);
System.out.println(liststudent);
} catch (Exception e) {
e.printStackTrace();
}
}
输出的sql结果:select * from t_student where age in (item,item),显示age为21、23的学生信息。
Settings 元素
Setting 元素下是些非常重要的设置选项,用于设置和改变 MyBatis 运行中的行为。下面的 表格列出了 Setting 元素支持的属性、默认值及其功能。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vuQc9cUw-1576746278488)(E:\javaEE笔记\img\QQ浏览器截图20191218153217.png)]
完整配置例子:
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="enhancementEnabled" value="false"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25000"/>
</settings>
XML 中的特殊字符
如果 MyBatis 使用 XML 配置,那不可避免地会遇到一些对 XML 来说是特殊的字符。如小于号 “<”,因为 XML 解析器会认为是一个新元素的开始,因此要进行转义。这里有两个方法:
1 使用转义实体
下面是五个在 XML 文档中预定义好的转义实体 :
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
select * from t_student where age $lt; 23
</select>
2 使用 CDATA 部件
一个 CDATA 部件以"“标记结束。在”"之间 的特殊字符的意义都不起作用,而转变为普通字符串内容。
一般地,在 MyBatis 的 XML 映射语句配置文件中,如果 SQL 语句有特殊字符,那么使用 CDTA 部件括起来,如:
<select id="findStudentList" parameterType="hashmap" resultMap="studentInfo">
<![CDATA[
select * from t_student where age = 23
]]>
</select>
而在动态 SQL 各元素的测试语句中,在元素的属性中不能再嵌套其它元素或包含 CDATA 部 件,因此只能使用转义实体, 如:
<select id="selectAuthor_use_where" parameterType="Blog" resultType="Author">
select * from author
<where>
<if test="authorId != null
and authorId >= 1
and authorId <= 5">
id = #{authorId}
</if>
</where>
</select>
以上就是如何在MyBatis中实现动态SQL,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。