- https://www.cnblogs.com/zhjh256/p/8512392.html">源码解读: https://www.cnblogs.com/zhjh256/p/8512392.html
- mybatis
- ">todo原理??暂时跟到这儿,有时间再看 ,
大概是 org.apache.ibatis.plugin.Interceptor 提供接口,支持插件
pagehelp实现该接口
QueryInterceptor.plugin 调用 Plugin._wrap 把自身传入_Plugin
org.apache.ibatis.plugin.Plugin 实现了InvocationHandler invoke 调用QueryInterceptor 最终调用到QueryInterceptor.intercept
源码解读: https://www.cnblogs.com/zhjh256/p/8512392.html
mybatis
springboot装配mybatis流程 ==待补充
概念
1:什么是mybatis
一种半ROM框架,实现数据库对象到java对象的转换,内部封装了jdbc链接,获取statement等操作,让程序员专注业务本身
基础
spring集成mybatis
直接用插件生成相关文件
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<!-- 配置文件 路径 -->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<phase>deploy</phase>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
</dependencies>
</plugin>
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator -config_1_0.dtd">
<generatorConfiguration>
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 -->
<classPathEntry location="/Users/luyinbin/.m2/repository/mysql/mysql-connector-java/5.1.47/mysql-connector-java-5.1.47.jar" />
<!-- 一个数据库一个context -->
<!--defaultModelType="flat" 大数据字段,不分表 -->
<context id="MysqlTables" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="autoDelimitKeywords" value="true"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<property name="javaFileEncoding" value="utf-8"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳-->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/company_frame" userId="root"
password="12345678"/>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator targetPackage="com.firstexample.lesson.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 生成mapxml对应client,也就是接口dao -->
<javaClientGenerator targetPackage="com.firstexample.lesson.mapper" targetProject="src/main/java" type="XMLMAPPER">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- <table tableName="sys_user" domainObjectName="SysUser"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="true">
<columnOverride column="sex" javaType="java.lang.Integer"/>
<columnOverride column="status" javaType="java.lang.Integer"/>
<columnOverride column="create_where" javaType="java.lang.Integer"/>
<columnOverride column="deleted" javaType="java.lang.Integer"/>
</table>-->
<table tableName="sys_dept" domainObjectName="SysDept"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="true">
<columnOverride column="status" javaType="java.lang.Integer"/>
<columnOverride column="deleted" javaType="java.lang.Integer"/>
</table>
<table tableName="sys_log" domainObjectName="SysLog"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="true">
</table>
<table tableName="sys_permission" domainObjectName="SysPermission"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="true">
<columnOverride column="type" javaType="java.lang.Integer"/>
<columnOverride column="status" javaType="java.lang.Integer"/>
<columnOverride column="deleted" javaType="java.lang.Integer"/>
</table>
<table tableName="sys_role" domainObjectName="SysRole"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="true">
<columnOverride column="status" javaType="java.lang.Integer"/>
<columnOverride column="deleted" javaType="java.lang.Integer"/>
</table>
<table tableName="sys_role_permission" domainObjectName="SysRolePermission"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="true">
</table>
<table tableName="sys_user_role" domainObjectName="SysUserRole"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="true">
</table>
<table tableName="sys_user" domainObjectName="SysUser"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="true">
</table>
</context>
</generatorConfiguration>
配置好后运行插件,会生成三个文件
1:xxxxmapper.xml 与数据库的交互,写sql的地方
2:xxxmapper.java 与springboot的交互接口 ,注入ioc容器中
3:xxx.java 一般与表名相同,数据库 到 service的实体映射,这个类中字段与表一一对应,也可以自定义~~
注意点:
1:xml中id 与 接口名保持一致
2:返回类型确保正确
3:映射字段修改正确
使用
1:写好sql
2:注入接口
3:调用
@Autowired
private SysLogMapper sysLogMapper;
@GetMapping("/select")
public SysLog select(@RequestParam("id") String id){
List<SysLog> sysLogs = sysLogMapper.selectAll();
SysLog sysLog = sysLogMapper.selectByPrimaryKey(id);
return sysLog;
}
三种实现方式
一:
1:定义接口,定义pojo对象
2:实现接口并集成SqlSessionDaoSupport
3:配置java bean 到 mapper.xml 的映射
4:获取sqlsession对象并执行
二:
接口映射,其实跟上面的一样,内置 MapperFactoryBean 集成了SqlSessionDaoSupport 实现方法getObject()获取到了mapper对象()getSqlSession().getMapper(this.mapperInterface); 根据接口对象获取
问题
1:mapper接口如何跟xml交互,过程
2:mapper接口如何跟业务层交互
主要是 MapperProxy 先从缓存获取方法(cachedInvoker)
如果没有则创建,
再调用public Object execute(SqlSession sqlSession, Object[] args)
最终还是调到sqlsession中的方法执行
这块代码有空再读
核心部件
MybatisAutoConfiguration
spring中的自动装配设置
其中实例化了 SqlSessionFactoryBean 获取 SqlSessionFactory对象 和
SqlSessionTemplate两个关键对象
Configuration
SqlSessionFactory /SqlSessionTemplate
SqlSessionFactoryBuilder
statement
Executor sql执行器
1:simple 每次执行创建一个新statment 并 commit 执行完后close —-默认执行器
2:Reuse 相比于simple。会缓存 statment。sql作为key,存在map
3: Batch 执行updata时 将所有sql都添加到批处理中(addBatch()),等待统一执行(executeBatch()),它缓存了多个Statement对象,每个Statement对象都是addBatch()完毕后,等待逐一执行executeBatch()批处理。与JDBC批处理相同。
作用范围:
Executor的这些特点,都严格限制在SqlSession生命周期范围内。
如何指定excutor
设置(settings)可以指定默认的ExecutorType执行器类型
SqlSession openSession(ExecutorType execType)
SqlSessionDaoSupport
获取sqlsession。可以自定义执行,如果不用mybatis接口映射方式,需要继承该类,通过 getSqlSession 拿到sqlsession
内置了MapperFactoryBean 继承该类,初始化是被加载进容器
mapper.xml 常用标签
1. if 条件判断
<if test = "条件">
代码块
</if>
2. where
可以理解为 sql 中的where 只有条件中1个以上生效才会拼接where,如果第一个条件and/or开头,自动处理
3. set
同sql中的set,动态凭借sql语句,可以出去前后不想关符号
- trim
类似String中的trim。处理sql语句
<trim prefix="(" prefixOverrides="and" suffie=")">
参数解释 prefix 前置处理 suffie后置处理 prefixOverrides删除前置符 suffieOverrides 删除后置符
5. choose when otherwise
类似java switch case 或者 if/else 由于mybatis不支持ifelse。可以用这代替 when 里带条件
<choose>
<when test="cxxx">
and ${xxxx}
</when>
<otherwise>
xxx
</otherwise>
</choose>
6. foreach
<foreach item="item" collection="list" index="index" open="" close="" separator=";">
## item 迭代别名
collection 迭代数组类型
index 如果为map时代表 key item代表value 数组则代表下标
open 开始标识
separator 分割符
close 结束
</foreach>
可以理解为groovy中 eachwithindex 吧所有结果放到 open close 中,以 separator分割
7. bind
绑定变量供上下文使用, 实现类似concat函数功能 比如进行模糊查询的参数拼接
<bind name="hah" value="'%' + id+'%' "></bind>
select * from sys_log where id like #{hah}
属性解释
name 理解为变量 value 理解为值
8. sql
9. parameterType 入参类型
10.parametermao map形式入参
11. resultMap map形式出参
12. resultType 出参映射类型
13. selectKey 一般配合insert语句使用,作为返回值
分页
1:用limit
@GetMapping("/selectAll")
public List<SysLog> selectAll(@RequestParam("page") int page,@RequestParam("pagesize") int pagesize){
int startPage = (page-1) *pagesize;
BaseQuery baseQuery = new BaseQuery(startPage, pagesize);
return sysLogMapper.selectAll(baseQuery);
}
select
<include refid="Base_Column_List"></include>
from
sys_log
limit #{curreyPage},#{pageSize}
2:插件 pagehelper
依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>1.0</version>
</dependency>
service层
PageHelper.startPage(page,pagesize);
List<SysLog> sysLogs = sysLogMapper.selectAll(); //紧跟着上面一条,如果有多条只有第一条有效
PageInfo<SysLog> sysLogPageInfo = new PageInfo<>(sysLogs); //封装详细数据,可以不写
return sysLogPageInfo;
todo原理??暂时跟到这儿,有时间再看 ,
大概是 org.apache.ibatis.plugin.Interceptor 提供接口,支持插件
pagehelp实现该接口
QueryInterceptor.plugin 调用 Plugin._wrap 把自身传入_Plugin
org.apache.ibatis.plugin.Plugin 实现了InvocationHandler invoke 调用QueryInterceptor 最终调用到QueryInterceptor.intercept

自定义数据源
遗留问题
1:spring 自动装配如何注入sqlsession https://blog.csdn.net/zxysshgood/article/details/113701377