SpringBoot整合Mybatis

Stella981
• 阅读 584

MyBatis的动态SQL是最令人喜欢的功能

在了解 动态SQL之前,你首先得知道一个表达式 OGNL,这个是基础!

SpringBoot整合Mybatis

  • 面试常问问题 : Mybatis 中$与#的区别?

  • #是将传入的值当做字符串的形式,select id,name,age from test where id =#{id},
    当把id值传入到后台的时候,就相当于 select id,name,age from test where id =‘1’.

  • ""是将传入的数据直接显示生成sql语句,selectid,name,agefromtestwhereid="是将传入的数据直接显示生成sql语句,select id,name,age from test where id = "是将传入的数据直接显示生成sql语句,selectid,name,agefromtestwhereid={id},
    当把id值1,传入到后台的时候,就相当于 select id,name,age from test where id = 1.

  • 使用#可以很大程度上防止sql注入。(语句的拼接)

if 标签

  • mapper

    select from test where 1=1 and username like concat('%', #{username}, '%') and ip=#{ip}

  • 在mapper 接口中映射这个方法

    List selectByTestSelective(Test example);

下面每个标签都会有对应的方法,但下文没有一一写出,现参考如下

List<Test> selectByExample(TestExample example);
List<Test> selectByTestSelective(Test example);
List<Test> selectByIdOrUserName(Test example);
List<Test> selectByTestSelectiveWhereTag(Test example);
List<Test> selectByTestIdList(List<Integer> ids);
int insertList(List<Test> students);
int updateTestSetTag(Test example);
int selectSelectiveTrim(Test example);
复制代码
  • 测试

    @RequestMapping(value = "/dongtaiSql")
    @ResponseBody
    public void dongtaiSql() {
        Test example = new Test();
        example.setUsername("周");
        List<Test> selectByTestSelective = testMapper.selectByTestSelective(example);
        for (Test test : selectByTestSelective) {
            System.out.println(test.getUsername());
        }
    }
    复制代码
    
  • 打印结果

SpringBoot整合Mybatis

  • 也就是说,你传什么值 它会根据你传的值来拼接sql,不传值则不拼接,这种相对来说比较简单,易于理解。

【注意】 下文所有的请求都是通过postman发出的。

SpringBoot整合Mybatis

include标签

  • 一个非常好用的辅助性标签,用于放一些公共的返回结果集,方便其他的查询方法使用,比如在mapper中使用方式如下:

    username, lastloginTime select from test where id = #{id,jdbcType=BIGINT}

choose标签 ,配合when ,otherwise 标签使用

choose when otherwise 标签可以帮我们实现 if else 的逻辑。一个 choose 标签至少有一个 when,
最多一个otherwise。

  • mapper

    select from test where 1=1 and id=#{id} and username=#{username} and 1=2

  • 打印结果

SpringBoot整合Mybatis

找不到 周 ,因为我只有周杰伦或者周杰 。 这个choose和 if 的功能有点类似,但是和if 不同的是choose 有点你有什么我就根据你给的查,而if 则是你传了所有条件,我逐个判断你的条件然后给你查。if 更多适用于表单查询的时候用。而choose 更多的时候。。。其实这两个达到的目的是一样的,我更喜欢用choose.

where 标签

  • mapper

    select from test and username like concat('%', #{username}, '%') and ip=#{ip}

  • 结果

SpringBoot整合Mybatis

  • 我什么条件也没传,他在where中找不到匹配的条件就查找了全部给了我,这种其实和上面choose 中的最后那个条件有异曲同工之处,上变改成1=1 一样的效果。

foreach 标签

  • mapper

    select from test where id in #{id}

  • 代码

    @RequestMapping(value = "/dongtaiSql3")
    @ResponseBody
    public void dongtaiSql3() {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        arrayList.add(6);
        arrayList.add(5);
        List<Test> selectByTestSelective = testMapper.selectByTestIdList(arrayList);
        for (Test test : selectByTestSelective) {
            System.out.println(test.getUsername());
        }
    }
    复制代码
    
  • 结果

SpringBoot整合Mybatis

  • 这个标签太好用了,foreach 也可以用来批量插入数据,比如:

  • mapper

    insert into test(username, gender, ip) values ( #{test.username}, #{test.gender},#{test.ip} )

  • 代码

    @RequestMapping(value = "/dongtaiSql4") @ResponseBody public void dongtaiSql4() { Test example = new Test(); example.setUsername("刘德华"); example.setGender(1); example.setIp("123232113111");

        Test example2 = new Test();
        example2.setUsername("郭富城");
        example2.setGender(1);
        example2.setIp("123232113122");
            
        Test example3 = new Test();
        example3.setUsername("邱淑贞");
        example3.setGender(0);
        example3.setIp("123232113333");
        ArrayList<Test> arrayList = new ArrayList<Test>();
        arrayList.add(example);
        arrayList.add(example2);
        arrayList.add(example3);
            
        int selectByTestSelective = testMapper.insertList(arrayList);
        if (selectByTestSelective == 1) {
            System.out.println("批量插入:"+arrayList.size()+"条数据");
        }
    } 
    复制代码
    
  • 结果

SpringBoot整合Mybatis

  • 妈的 这里的mapper 每次修改都要重新启动,很是麻烦。注意这里 #{test.username}, #{test.gender},#{test.ip} 最后不要有逗号,否则会报一个sql语法错误,原因是多了,。还有就是这里如果传的值是list等非实体类的参数的时候,是不用声明parameterType 的。

  • foreach 的变量说明

    collection: 必填, 集合/数组/Map的名称. item: 变量名。即从迭代的对象中取出的每一个值 index: 索引的属性名。当迭代的对象为 Map 时, 该值为 Map 中的 Key. open: 循环开头的字符串 close: 循环结束的字符串 separator: 每次循环的分隔符

bind 标签

  • 使用 bind 来让该 SQL 达到支持两个数据库的作用

  • mapper

    select from test where 1=1 and username like #{nameLike} and ip=#{ip}

  • 代码

    @RequestMapping(value = "/dongtaiSql") @ResponseBody public void dongtaiSql() { Test example = new Test(); example.setUsername("周"); List selectByTestSelective = testMapper.selectByTestSelective(example); for (Test test : selectByTestSelective) { System.out.println(test.getUsername()); } }

  • 结果

SpringBoot整合Mybatis

发现依然可以。 说明这个bind 就是绑定一些变量的 ,nameLike 就代表了username 的模糊搜索,就是如果别的地方用得到它的模糊搜索,拿来用即可。用法是 like 后面直接加上 #{nameLike }。

set 标签

这个标签常用于做修改语句,比如

  • mapper

    UPDATE Products username = #{username}, ip = #{ip}, id = #{id}

  • 代码

    @RequestMapping(value = "/dongtaiSql5") @ResponseBody public void dongtaiSql5() { Test example = new Test(); example.setUsername("周"); example.setIp("cium"); example.setId(27); int selectByTestSelective = testMapper.updateTestSetTag(example); System.out.println(selectByTestSelective);

    } 
    复制代码
    
  • 结果

SpringBoot整合Mybatis

  • 这个set 说白了就是update语句的 set 时候的一个灵活操作。

trim 标签

  • mapper

    select * from test          AND username=#{username}      AND ip=#{ip}   

  • 【注意】

  • 这里有很多坑,首先mybatis-plus 中不是 prefixoverride 而是prefixOverrides

  • 然后"AND |OR" 必须有空格,原因如下图

  • 如果 ip 不是字符串就不能用length() 方法

SpringBoot整合Mybatis

trim标签各参数的说明

prefix:在trim标签内sql语句加上前缀。
suffix:在trim标签内sql语句加上后缀。
prefixOverrides:指定去除多余的前缀内容
suffixOverrides:指定去除多余的后缀内容,如:suffixOverrides=",",去除trim标签内sql语句多余的后缀","。 
复制代码

SpringBoot整合Mybatis

然而我在配置的时候却遇到了更坑的问题,迟迟得不到解决…欢迎有兴趣的朋友一起交流下解决最后这个问题。

最后

感谢大家看到这里,文章有不足,欢迎大家指出;如果你觉得写得不错,那就给我一个赞吧。

最后的最后,小编还给大家整理了一套面试宝典,有需要的小伙伴只需要添加小编的vx:mxzFAFAFA即可免费获取!

SpringBoot整合Mybatis

SpringBoot整合Mybatis

SpringBoot整合Mybatis

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Easter79 Easter79
2年前
SpringBoot整合Mybatis
MyBatis的动态SQL是最令人喜欢的功能在了解动态SQL之前,你首先得知道一个表达式OGNL,这个是基础!!在这里插入图片描述(https://p3juejin.byteimg.com/toscnik3u1fbpfcp/71e4f99be1254c7
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
2个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这