MyBatis操作数据库(入门)
一.MyBatis的简单介绍
MyBatis(原名iBatis)是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。
中文网文档:MyBatis中文网
二.MyBatis的使用
1.配置文件
2.代码
三.测试类
1.Before,After注解
一个测试类
两个测试类
四.MyBatis基础操作
1.打印日志
首先配置yml文件,也可以配置properties文件,这里使用yml文件:
添加打印日志前:
添加打印日志后:
2.查询的参数传递
传递一个参数的写法:
再写到测试类中:
传递多个参数第一种写法:
第二种写法:

第三种写法:
3.插入的传递对象
第一种写法:
MyBatis会直接拆分对象里面的字段来进行匹配
第二种写法:
添加了Param注解后,它被默认为只传一个参数,字段信息需要手动通过 . 来进行传递。
获得自增Id
4.删除
5.修改
通过对象修改:



五.数据库字段和Java字段不同的写法转换
1.通过as进行转换
2.Results注解
3.ResultMap
复用Results注解里面的信息:
4.配置方式
六.MyBatis XML配置文件
1.yml的配置文件:
2.xml文件配置
红线圈的部分,是根据你定义的接口路径来选择的。
3.查询信息
(1).xml配置
(2).方法


(3).数据库和Java字段不同的处理方式:
(i) 通过as
(ii)使用xml

(iii)配置
4.插入信息
(1)xml配置
(2)Insert实现


当使用Param注解时,需要通过 . 来进行字段的分配:
(3)自增id
5.修改
1.需要注意别写错。
6.删除


七.多表查询
1.多表查询的准备:
2.使用时需要注意字符串拼接时,末尾加空格:

八.#和$差别
1.#为预编译SQL
2.$为即使SQL
3.$的注意事项
(1) 当使用$传递字符串的时候,需要加入引号,不然属于BadSQL语句:
所以使用$传递字符串时,需要加''号进行传递:
4.#和$最大的差别在于$会被SQL注入:
(1)$被注入攻击的SQL' or 1='1:
(2)#被注入攻击的SQL' or 1='1:

(3)排序只能用$因为#会自动给字符串增加引号
但是需要注意SQL的注入问题,这里可以使用枚举或者校验参数的方式来防止SQL的注入攻击。

(4)like模糊查询
如果like模糊查询会引起SQL注入,就没办法继续使用like,可以使用拼接。
(5)拼接

九.数据库连接池
1.介绍
数据库连接池负责分配、管理和释放数据库连接,它允许应⽤程序重复使⽤⼀个现有的数据库连接,⽽不是再重新建⽴⼀个.
常⻅的数据库连接池:
• C3P0
• DBCP
• Druid
• Hikari