Mybatis基于xml的动态sql实现
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Mybatis基于xml的动态sql实现,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2519字,纯文字阅读大概需要4分钟。
内容图文
![Mybatis基于xml的动态sql实现](/upload/InfoBanner/zyjiaocheng/887/72e8d34bffbe472a96e170d71db0744d.jpg)
动态sql可以很方便的拼接sql语句,主要用于复合条件查询;
主要通过这几个标签实现:
if 标签:
<select id="selectStudentByIf" resultType="Student"> select id,name,age,score from student where 1=1 <if test="name != null and name != ''"> and name like '%' #{name} '%' </if> <if test="age > 0"> and age < #{age} </if> </select>
使用if标签判断参数,可以使用where 1=1,后面跟上if标签,这样可以避免因为‘and’导致sql语句冲突;
where 标签
<select id="selectStudentByWhere" resultType="Student"> select id,name,age,score from student <where> <if test="name != null and name != ''"> and name like '%' #{name} '%' </if> <if test="age > 0"> and age < #{age} </if> </where> </select>
由于使用where 1=1 对查询性能也有一定的影响;可以使用where嵌套 if 标签,可以不需要使用上面“where 1=1”;
where标签会自动过滤掉if标签里sql语句的第一个and连接词;
作用:用来简化SQL语句中的where条件,可以嵌套其他标签;
choose标签:
<select id="selectStudentByChoose" resultType="Student"> select id,name,age,score from student <where> <choose> <when test="name != null and name != ''"> name like '%' #{name} '%' </when> <when test="age > 0"> age < #{age} </when> <otherwise> 1 != 1 </otherwise> </choose> </where> </select>
表示:
当查询条件有name时,不管有没有age,都只按name查询;
当查询条件没有name时,才按age进行查询;
当name和age都没有时,查询不到任何数据。
作用:类似于switch语句,选择多个条件中的一个;
foreach标签:
foreach用来遍历,遍历的对象可以是数组,也可以是集合。
属性:
collection可以指定遍历对象的类型:array,list
item是指定的集合中每一个元素迭代时候的别名;
separator表示在每次进行迭代之间以什么符号作为分隔符;
open表示该语句以什么开始,close表示以什么结束;
<select id="selectStudentByForeachArray" resultType="Student"> select id,name,age,score from student <if test="array != null and array.length > 0"> where id in <foreach collection="array" item="id" open="(" close=")" separator=","> #{id} </foreach> </if> </select>
表示遍历一个数组,迭代别名为id;
<select id="selectStudentByForeachList" resultType="Student"> select id,name,age,score from student <if test="list != null and list.size > 0"> where id in <foreach collection="list" item="id" open="(" close=")" separator=","> #{id} </foreach> </if> </select>
遍历一个list集合;
<select id="selectStudentByForeachList2" resultType="Student"> select id,name,age,score from student <if test="list != null and list.size > 0"> where id in <foreach collection="list" item="stu" open="(" close=")" separator=","> #{stu.id} </foreach> </if> </select>
遍历一个list,list中每个元素为对象;遍历对象的id属性;
内容总结
以上是互联网集市为您收集整理的Mybatis基于xml的动态sql实现全部内容,希望文章能够帮你解决Mybatis基于xml的动态sql实现所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。