资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

怎么在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


  select * from mybatis.bolg where 1=1
  
    and title = #{title}
  
  
    and author = #{author}
  
@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)


  select * from mybatis.bolg
  
    
      
        title=#{title}
      
      
        and author = #{author}
      
      
        and views = #{views}
      
    
  

4、trim(where,set)

select * from mybatis.bolg


  title = #{title}


  and author = #{author}


  update mybatis.bolg
  
    
      title = #{title},
    
    
      author = #{author},
    
  
  where id = #{id}

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一些逻辑代码

5、Foreach

select * from user where 1=1 and 
 
    #{id}
 

(id=1 or id=2 or id=3)

怎么在MyBatis中配置动态SQL



  select * from mybatis.bolg

  
  
    id = #{id}
  
  

SQL片段

有的时候,我们可能会将一些公共的部分抽取处理,方便复用

使用SQL标签抽取公共的部分


  
    title = #{title}
  
  
    and author = #{author}
  

在需要使用的地方使用Include标签引用即可


  select * from mybatis.bolg
  
    
  

上述内容就是怎么在MyBatis中配置动态SQL,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联行业资讯频道。


名称栏目:怎么在MyBatis中配置动态SQL
新闻来源:http://cdkjz.cn/article/igcsep.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220