1、认识MyBatis
Mybatis is a first class persistence framework with support for custom SQL,stored Procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJO(Plain Old Java Objects) to database records.
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
2、使用mybatis
A.作用域SCOPE生命周期
B.XML
(1)Generator 生成代码 http://www.mybatis.org/generator/quickstart.html
i、引入plugin
ii、generatorConfig.xml
Iii.执行 mvn mybatis-generator : generate
(2)Xml 与annotation 对比
3、Mybatis配置文件
Mapper.Xml 配置文件
resultType 直接返回到实体类
resultMap 联合查询
Sql 公用和复用的东西
分页
1、逻辑分页 把所有的结果查出来进行分页 相当于内存分页(不可取)
2、物理分页 如:Select.... limit 0,10
通常做法就是前段传来pageIndex 和pageSize 进行拼sql
分页插件 如pageHelper
批量操作 Batch 批量查询数据,批量更新数据
3、联合查询
a)嵌套结果(就是join) 不存在n+1 问题
1对1 的嵌套结果
b) 嵌套查询 存在n+1问题 一对多的属性在多的这一边 对多的一边会有多次查询,避免n条数据的查询可以启动懒加载
1对1
1对N
一对1 与 1对多的sql 是一样的,结果集不一样
4、缓存
一级缓存
一级缓存是默认开启的
每次查询都会需要一个sqlSession,一级缓存是基于sqlSession 级别的即线程级别的
第二次查询会命中第一次的缓存
1、为什么会使用一级缓存?
减小数据库压力
2、如何验证有一级缓存 ?
同一个sqlSession去查询两次,第二次不会进行数据库的访问
3、一级缓存有没有问题?
若在一个sqlSession的两次查询之间进行了数据的更新,就会导致第二次从缓存中获取的是脏数据
二级缓存
二级缓存默认是关闭的,也不建议使用,一般用redis三方代替
二级缓存是基于namespce的,也就是说基于mapper.xml的
关联查询写在哪个namespace下,关联查询就属于哪个结果
二级缓存是基于namespace的,若要开启二级缓存就要在相应的namespace中打开
二级缓存如何验证:
开启多个sqlSession 去查询同一个方法,将第一次查询的耗时,和后几次查询的耗时作对比。
二级缓存的问题:
- 非常容易出现脏数据
- 失效问题,全部失效,更新的话是全部失效(就是id=1的变了,其他也全部都变了)
5、mybaits中用的到设计模式
-
Builder模式 :
例如
SqlSessionFactoryBuilder
、XMLConfigBuilder
、XMLMapperBuilder
、XMLStatementBuilder
、CacheBuilder
; -
工厂模式 :
例如
SqlSessionFactory
、ObjectFactory
、MapperProxyFactory
; -
单例模式 :例如
ErrorContext
和LogFactory
; -
代理模式 :Mybatis实现的核心,比如
MapperProxy
、ConnectionLogger
,用的jdk的动态代理;还有executor.loader
包使用了cglib或者javassist达到延迟加载的效果; -
组合模式 :例如
SqlNode
和各个子类ChooseSqlNode
等; -
模板方法模式 : 例如
BaseExecutor
和SimpleExecutor
,还有BaseTypeHandler
和所有的子类例如IntegerTypeHandler
; -
适配器模式 : 例如Log的Mybatis接口和它对jdbc、log4j等各种日志框架的适配实现;
-
装饰者模式 : 例如
cache
包中的cache.decorators
子包中等各个装饰者的实现; -
迭代器模式 : 例如迭代器模式
PropertyTokenizer
;