1. MyBatis的介绍
- MyBatis将重要的步骤抽取出来可以人工定制,是一个半自动化的持久化层的轻量级框架;
- 重要步骤都是写在配置文件中,好维护;
- 完全解决数据库的优化问题;
- MyBatis底层就是对原生JDBC的一个简单封装;
- 既将Java编码与SQL抽取出来,功能边界清晰,一个专注业务,一个专注数据;
- MyBatis的GitHub地址: https://github.com/mybatis/mybatis-3
- MyBatis的官方文档地址:https://mybatis.org/mybatis-3/zh/index.html
2. 注解
- @Param("") 标注在对应形参前,当传入多个参数时,MyBatis会将参数封装到一个Map中,但是key是param1,param2...paramN,在拼接sql时,我们需要找对哪个是第一个哪个是第二个,#{param1}#{param2}...#{paramN},而且不能见名知义。那么我们可以自己指定每个值对应的key是什么,比如getEmpByIdAndLastName(@Param("id") Integer id,@Param("lastName") String lastName),在拼接SQL时,直接使用#{id}和#{lastName},不用关心他们的位置,而且见名知义;
- @MapKey("") 标注在接口方法上,表示返回的Map结果中,用哪个数据库字段的值当作key;
- @Select
- @Update
- @Delete
- @Insert
3. MyBatis取值的两种方式
- #{属性名} 参数的位置用?号代替,是预编译的方式;不会有SQL注入问题
- ${属性名} 直接和SQL语句进行拼接;一般用于动态传入有规律的表名(log_20201103,log_20201104)、排序等;使用时想办法避免SQL注入;
4. MyBatis的缓存机制
- MyBatis有两级缓存,默认开启着一级缓存(SqlSession级别的缓存)
- 一级缓存失效的4种情况:
- SqlSession不同;
- SqlSession相同,查询条件不同;
- SqlSession相同,查询期间有执行增删改操作;
- 清空了一级缓存 clearCache()
- 二级缓存需要手动开启,是基于namespace级别的缓存,一个namespace对应一个二级缓存
- 一级缓存关闭后,会把数据放到二级缓存中;在查询时,先查二级再看一级;
5. MyBatis与Spring、SpringMVC的整合
6. 逆向工程
- 官方地址 https://github.com/mybatis/generator
- 自动生成的代码,并不意味着需要的方法都有,有时我们还是会根据业务自己调整一下;
- Demo代码:https://github.com/zmjjobs/MyBatis_demo.git
7. MyBatis运行原理与源码分析
7.1 SqlSessionFactory的初始化
7.1.1 通过SqlSessionFactoryBuilder里面的build方法创建SqlSessionFactory
public SqlSessionFactory build(InputStream inputStream) {
return build(inputStream, null, null);
}
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
}
}
}
7.1.2 进入build(parser.parse())里面的parser.parse()方法
进入XMLConfigBuilder类,对应mybatis-config.xml的根标签<configuration>,并解析这个标签下的所有内容
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
7.1.3 parseConfiguration(XNode root)解析标签<configuration>下的所有内容
这里对应着xml里面的每个标签,并对每个标签的子标签进行解析,并赋值到Configuration对象中
private void parseConfiguration(XNode root) {
try {
// issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
loadCustomLogImpl(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
7.1.4 返回Configuration对象后,执行build(Configuration config)
返回包含有Configuration对象的DefaultSqlSessionFactory对象
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
7.2 SqlSessionFactory的调用openSession()开启一个SqlSession
7.2.1 SqlSessionFactory是一个接口,它的默认实现类是DefaultSqlSessionFactory
######DefaultSqlSessionFactory类
@Override
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final Executor executor = configuration.newExecutor(tx, execType);
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
7.2.2 进入transactionFactory.newTransaction新建一个事务
public class JdbcTransactionFactory implements TransactionFactory {
@Override
public Transaction newTransaction(Connection conn) {
return new JdbcTransaction(conn);
}
@Override
public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
return new JdbcTransaction(ds, level, autoCommit);
}
}
public class JdbcTransaction implements Transaction {
private static final Log log = LogFactory.getLog(JdbcTransaction.class);
protected Connection connection;
protected DataSource dataSource;
protected TransactionIsolationLevel level;
protected boolean autoCommit;
public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
dataSource = ds;
level = desiredLevel;
autoCommit = desiredAutoCommit;
}
}
7.2.3 进入configuration.newExecutor(tx, execType) 新建一个SIMPLE类型的执行器
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
7.3 sqlSession.getMapper(XxxMapper.class)
7.3.1 接口实现的默认是DefaultSqlSession.getMapper
#####DefaultSqlSession类
public <T> T getMapper(Class<T> type) {
return configuration.getMapper(type, this);
}
7.3.2 进入Configuration的configuration.getMapper(type, this)
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
7.3.3 进入MapperRegistry的mapperRegistry.getMapper(type, sqlSession)生成代理对象
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
7.4 employeeMapper.getEmpById(1) 也就是对应接口的Employee getEmpById(Integer id)
7.4.1 进入MapperProxy的invoke方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else {
return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
7.4.2 进入cachedInvoker(method).invoke(proxy, method, args, sqlSession) 也就是MapperProxy的cachedInvoker(Method method)
private MapperMethodInvoker cachedInvoker(Method method) throws Throwable {
try {
// A workaround for https://bugs.openjdk.java.net/browse/JDK-8161372
// It should be removed once the fix is backported to Java 8 or
// MyBatis drops Java 8 support. See gh-1929
MapperMethodInvoker invoker = methodCache.get(method);
if (invoker != null) {
return invoker;
}
return methodCache.computeIfAbsent(method, m -> {
if (m.isDefault()) {
try {
if (privateLookupInMethod == null) {
return new DefaultMethodInvoker(getMethodHandleJava8(method));
} else {
return new DefaultMethodInvoker(getMethodHandleJava9(method));
}
} catch (IllegalAccessException | InstantiationException | InvocationTargetException
| NoSuchMethodException e) {
throw new RuntimeException(e);
}
} else {
return new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
}
});
} catch (RuntimeException re) {
Throwable cause = re.getCause();
throw cause == null ? re : cause;
}
}
7.4.3 后面会进入到MapperProxy的invoke
public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
return mapperMethod.execute(sqlSession, args);
}
7.4.4 点击mapperMethod.execute 进入 MapperMethod.execute,也就是执行增删改查的方法
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
if (method.returnsOptional()
&& (result == null || !method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
7.4.5 进入sqlSession.selectOne,实现是DefaultSqlSession.selectOne
public <T> T selectOne(String statement, Object parameter) {
// Popular vote was to return null on 0 results and throw exception on too many.
List<T> list = this.selectList(statement, parameter);
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
public <E> List<E> selectList(String statement, Object parameter) {
return this.selectList(statement, parameter, RowBounds.DEFAULT);
}
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
return executor.query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
7.4.6 进入configuration.getMappedStatement(statement) 也就是Configuration.getMappedStatement拿到MappedStatement对象
public MappedStatement getMappedStatement(String id) {
return this.getMappedStatement(id, true);
}
public MappedStatement getMappedStatement(String id, boolean validateIncompleteStatements) {
if (validateIncompleteStatements) {
buildAllStatements();
}
return mappedStatements.get(id);
}
7.4.7 点击executor.query进入CachingExecutor.query
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameterObject);
CacheKey key = createCacheKey(ms, parameterObject, rowBounds, boundSql);
return query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
Cache cache = ms.getCache();
if (cache != null) {
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, boundSql);
@SuppressWarnings("unchecked")
List<E> list = (List<E>) tcm.getObject(cache, key);
if (list == null) {
list = delegate.query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
}
7.4.8 进入BaseExecutor.query
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
if (queryStack == 0 && ms.isFlushCacheRequired()) {
clearLocalCache();
}
List<E> list;
try {
queryStack++;
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
} finally {
queryStack--;
}
if (queryStack == 0) {
for (DeferredLoad deferredLoad : deferredLoads) {
deferredLoad.load();
}
// issue #601
deferredLoads.clear();
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
// issue #482
clearLocalCache();
}
}
return list;
}
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
7.4.9 进入SimpleExecutor.query,然后就明白了
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
8. MyBatis重要的标签
<select id="" resultMap="" resultType=""> <bind name="_xxx" value="'%' + xxx+ '%'"/> SQL语句 </select> | 查询:id对应接口方法名;resultMap是指定自定义结果集;resultType是返回一个指定对象的全类名;resultMap和resultType二选一; 如果遇到模糊查询,可以使用bind 标签,xxx为传入属性名,在sql语句中赋值为#{_xxx} |
<insert id="" useGeneratedKeys="true" keyProperty=""> SQL语句</insert> | 插入:id对应接口方法名;useGeneratedKeys如果为true则在返回的对象中会带有自增主键值;keyProperty主键值要赋值到哪个属性上 |
<update id="">SQL语句</update> | 更新:id对应接口方法名 |
<delete id="">SQL语句</delete> | 删除:id对应接口方法名 |
<sql id="">SQL字段</sql> <include refid=""/> | 将一些可以重用的SQL字段提取到sql标签中,然后通过include来引用 |
<resultMap type="" id=""> <id property="" column=""/> <result property="" column=""/> <association property="" javaType=""> <id property="" column=""/> <result property="" column=""/> </association> </resultMap> | resultMap 自定义结果集;type是这个结果集对应的对象A;id是将来查询时resultMap对应的值; id是此表a的主键,property是此对象A属性;column是此表a的列名; result是此表a的其他字段,property是此对象A的其他属性;column是此表a的其他列名; association 是这个对象A里面包含的另外一个对象B,property是对象B在对象A中的属性名,javaType是这个对象B的全类名;
|
<where> <if test=""> </where> | where条件,if判断;默认会把条件中的第一个and去掉; |
<set> <if test=""> </set> | set更新部分,if判断;默认会把条件中最后一个逗号去掉; |
<resultMap type="" id=""> <id property="" column=""/> <result property="" column=""/> <collection property="" ofType=""> <id property="" column=""/> <result property="" column=""/> </collection> </resultMap> | resultMap 自定义结果集;type是这个结果集对应的对象A;id是将来查询时resultMap对应的值; id是此表a的主键,property是此对象A属性;column是此表a的列名; result是此表a的其他字段,property是此对象A的其他属性;column是此表a的其他列名; collection 是这个对象A里面包含的另外一个对象B集合,property是对象B集合在对象A中的属性名,ofType是这个对象B的全类名; |