Mybatis-08-动态SQL

动态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

创建一个基础工程

  1. 导包

  2. 编写配置文件

  3. 编写实体类

    @Data
    public class Blog {
        private int id;
        private String title;
        private String author;
        private Date date;
        private int views;
    }
    
  4. 编写对应的Mapper接口和MapperXML文件

IF


choose(where,otherwise)


    
		title=#{title}
	
    
    	and views=#{views}
    


trim(where,set)



    update blog
    
        
            title=#{title},
        
        
            auther=#{auther}
        
    

所谓的动态SQL,本质还是SQL语句,只是在SQL层面增加逻辑代码。

**SQL片段 **

  1. 使用SQL标签抽取公共部分

    
        and title=#{title}
    
    
        and auther=#{auther}
    

  1. 在需要使用的地方使用include标签引用
select * from mybatis.blog

注意事项:

  • 最好基于单表来定义SQL片段
  • 不要存在where标签

Foreach

Mybatis-08-动态SQL_第1张图片

你可能感兴趣的:(Mybatis-08-动态SQL)