怎么在MyBatis中配置动态SQL
本篇文章为大家展示了怎么在MyBatis中配置动态SQL,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:做网站、成都做网站、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的莘县网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!
动态SQL
什么是动态SQL:
动态SQL就是根据不同的条件生成不同的SQL语句
if
choose(when,otherwise)
trim(where,set)
foreach
1、搭建环境
建表
CREATE TABLE `bolg`( `id` VARCHAR(50) NOT NULL COMMENT '博客id', `title` VARCHAR(100) not null comment '博客标题', `author` VARCHAR(30) not null comment '博客作者', `creat_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 creatTime;
private int views;
}编写实体类对应的Mapper接口和Mapper.xm
2、IF
@Test
public void queryBlogIF(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("author","尹锐");
List blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
} 3、choose(when,otherwise)
4、trim(where,set)
select * from mybatis.bolgtitle = #{title} and author = #{author}
update mybatis.bolg where id = #{id} title = #{title}, author = #{author},
所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一些逻辑代码
5、Foreach
select * from user where 1=1 and#{id} (id=1 or id=2 or id=3)

SQL片段
有的时候,我们可能会将一些公共的部分抽取处理,方便复用
使用SQL标签抽取公共的部分
title = #{title} and author = #{author}
在需要使用的地方使用Include标签引用即可
上述内容就是怎么在MyBatis中配置动态SQL,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。
网站名称:怎么在MyBatis中配置动态SQL
网站地址:http://www.jxjierui.cn/article/igcsep.html


咨询
建站咨询
