Mybatis-08-动态SQL
2024-08-28 21:53:41
动态SQL
什么是动态SQL?
根据不同的条件生成不同的SQL语句。
if
choose(where,otherwise)
trim(where,set)
foreach
搭建环境
create table `blog`(
`id` varchar(50) not null comment '博客id',
`title` varchar(100) not null comment '博客标题',
`auther` varchar(30) not null comment '博客作者',
`create_time` datetime not null comment '创建时间',
`views` int(30) not null comment '浏览量'
)engine =innodb default charset =utf8
创建一个基础工程
导包
编写配置文件
编写实体类
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date date;
private int views;
}
编写对应的Mapper接口和MapperXML文件
IF
<select id="queryBlogIf" resultType="blog" parameterType="map">
select * from mybatis.blog where 1=1
<if test="title!=null">
and title=#{title}
</if>
<if test="auther!=null">
and auther=#{auther}
</if>
</select>
choose(where,otherwise)
<choose>
<when test="title!=null">
title=#{title}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
trim(where,set)
<select>
select * from mybatis.blog
<where>
<if test="title!=null">
and title=#{title}
</if>
<if test="auther!=null">
and auther=#{auther}
</if>
</where>
</select>
<update id="updataBlog" parameterType="map">
update blog
<set>
<if test="title!=null">
title=#{title},
</if>
<if test="auther!=null">
auther=#{auther}
</if>
</set>
</update>
所谓的动态SQL,本质还是SQL语句,只是在SQL层面增加逻辑代码。
**SQL片段 **
- 使用SQL标签抽取公共部分
<sql id="if-title-auther">
<if test="title!=null">
and title=#{title}
</if>
<if test="auther!=null">
and auther=#{auther}
</if>
</sql>
- 在需要使用的地方使用include标签引用
select * from mybatis.blog
注意事项:
- 最好基于单表来定义SQL片段
- 不要存在where标签
Foreach
最新文章
- 关于Unity3D手机网游开发一些小看法
- U盘插入电脑后,提示需要格式化U盘如何解决?
- 我的ORM之十二 -- 支持的数据库及差别
- java开发中的一些工具软件
- [NOIP2010] 提高组 洛谷P1540 机器翻译
- hdu2955
- docker rabbitmq
- php的递归函数
- Error: theForm.submit is not a function !!
- Loadrunner11点击录制脚本无响应,IE页面弹不出——解决方案汇总
- 认识input输入框的placeholder属性
- 【Hibernate步步为营】--复合主键映射具体解释
- respondsToSelector
- Eclipse 基础操作与设置
- Java容器:List
- VS 编译通过后 链接提示 无法使用的外部符号
- Unity Editor 下创建Lua和Text文件
- Codeforces | CF1037D 【Valid BFS?】
- 第十四章 Java常用类
- unity, Collider2D.bounds的一个坑