mybatis的概述
是一个ORM框架。
原理和代码阅读
MyBaits原理
https://www.cnblogs.com/luoxn28/p/6417892.html
sqlSessionFactory会根据配置文件和mapper文件创建sqlsession,
使用JDK对接口创建代理,
然后底层调用JDBC执行。
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);
}
}
//创建代理对象
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
上面的mapperProxy是创建的代理辅助类。MapperProxy中并不向我们日常使用中存在一个被代理对象。而是读取配置调用JDBC完成。
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
private MapperMethod cachedMapperMethod(Method method) {
MapperMethod mapperMethod = methodCache.get(method);
if (mapperMethod == null) {
mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
methodCache.put(method, mapperMethod);
}
return mapperMethod;
}
}
Mybaits的缓存
- 一级缓存: 基于PerpetualCache 的 HashMap本地缓存,其存储作用域为 Session,当 Session flush 或 close 之后,该Session中的所有 Cache 就将清空。一级缓存是默认开启的。
- 二级缓存与一级缓存其机制相同,默认也是采用 PerpetualCache,HashMap存储,不同在于其存储作用域为 Mapper(Namespace),并且可自定义存储源,如 Ehcache。二级缓存是默认关闭的。
- 对于缓存数据更新机制,当某一个作用域(一级缓存Session/二级缓存Namespaces)的进行了 C/U/D 操作后,默认该作用域下所有 select 中的缓存将被clear。
为减少访问数据库的次数,当Session缓存中对象的属性发生变化时,并不会及时清理缓存及执行相关的SQL Update语句,而是在特定的时间点把相关的SQL合并为一条SQL语句才清理缓存。
当然,使用一级缓存会带来无法读到最新数据的问题。mybaits可以在mapper文件中对指定sql关闭缓存,这样这个sql每次就会取查询数据库了。
应用
使用
一个典型的配置如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
要写一个Mapper的文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
上面#号表示嵌入。#会在嵌入的变量上加“”。如果你使用$符则不会,但是你要小心sql注入。
一个典型的使用如下
SqlSession session = sqlSessionFactory.openSession();
try {
Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
} finally {
session.close();
}
插件
关于Mybatis中插件的声明需要在configuration的配置文件中进行配置。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<plugins>
<plugin interceptor="com.interceptors.LogInterceptor" ></plugin>
</plugins>
</configuration>
public class LogInterceptor implements Interceptor{
//被拦截时要执行的方法
@Override
public Object intercept(Invocation invocation) throws Throwable {
System.out.println("LogInterceptor : intercept");
return null;
}
//对目标对象的包装,可以返回对象的代理,也可以返回对象本身
@Override
public Object plugin(Object target) {
if(target instanceof StatementHandler){
RoutingStatementHandler handler = (RoutingStatementHandler)target;
//打印出当前执行的sql语句
System.out.println(handler.getBoundSql().getSql());
}
return target;
}
//配置文件
@Override
public void setProperties(Properties properties) {
System.out.println("LogInterceptor : setProperties");
}
}
Mybatis和Spring整合
主要配置如下,是通过MapperScannerConfigurer类扫描所有mapper文件。
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.ezca.autocount.dao"/>
<property name="markerInterface" value="org.ezca.autocount.dao.CertRegionMapper"/>
</bean>
spring + mybatis + zdal的系统调用链路。