01-动态sql
1.实现动态条件SQL
第一种方法在sql语句中加入where 1=1其他条件都加and就行,这样就可以根据if条件来判断要传递的参数可以有几个




第二种方法用where标签给if语句包起来
where标签的作用如下图



第三种方法用trim标签解释如下图

用choose也可以实现条件查询如下图,when解释测试类里的deptName的值也就是接口里参数的值,如果对应到下面的经理或者员工就输出对应的sql语句,如果都没对应上就输出otherwise标签的内容
注意博主亲自测试过参数只有一个的情况下test后面的deptName和otherwise标签里#{id}里面的名字写成什么都可以




foreach循环的使用由于我们要查询多条数据可以用到foreach,foreach里的collection表示在测试类中传入的字符串数组名,看第三张图里的newString[],然后这个数组在xml文件里吗是我们给其的名字所以我们需要再接口中给这个变量名声明进去就是给它起个usernames的别名,item表示每次返回的一个对象,separator表示分割符,open表示循环开始的字符串,close表示循环结束的字符串,index表示传进来参数的下标



set的用法 set用在update里面用于sql语句自动添加set关键字和去除最后一个更新字段的逗号

mybatis要实现模糊查询的方法
第一种模糊查询需要用到%符号,我们用空格拼接的方法来进行模糊查询如下图两个%之间有空格

第二种方法可以通过在测试类中拼接好来完成


第三种方法用bind设置个变量,里面传入值然后赋给#{},也能实现模糊查询

sql片段,减少重复代码,用法声明sql标签把重复用的sql语句方法标签里,然后想用的时候就用include refid=sql标签里的id名就行

sql标签还可以在查询的过程中设置查询的字段用include标签里面的property name属性可以随便赋值,value为你要查的数据库字段的名字,注意的是数据库字段里的名字,想要查多个参数可以用逗号然后写你要查的数据库字段,看下下图



mybatis批量插入的方法

创建1000条数据方法
第一种list集合中,然后用for循环批量调用接口的方法实现批量插入

第二种用foreach标签来实现逐条插入
首先在测试类中遍历一个list集合里面存入了1000个emp的数据

然后再.xml文件中用foreach 里的collection来接受传过来的1000个emp数据(注意用collection需要再接口上起个别名和collection属性名字一样的别名),如下下图所示


最后调用inserBatch接口方法实现批量插入
