RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
怎么在MyBatis中配置动态SQL-创新互联

本篇文章为大家展示了怎么在MyBatis中配置动态SQL,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

创新互联是专业的襄阳网站建设公司,襄阳接单;提供成都做网站、网站制作、成都外贸网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行襄阳网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

动态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,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联网站建设公司行业资讯频道。

另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


当前标题:怎么在MyBatis中配置动态SQL-创新互联
链接分享:http://sczitong.cn/article/ccopei.html