文章目錄
前言
學習一個框架除了搞清楚核心原理外,還有很關鍵的需要知道如何去擴展它,而對Mybatis來說,它提供了插件的方式幫助我們進行功能擴展,所以學習如何自定義一個插件也是非常有必要的,本文介紹一個基于插件如何實現一個分表的操作,相信從這個示例的學習,讀者會有些收獲的。本文還介紹了Spring如何與Mybatis整合的原理,幫助讀者更多的了解Mybatis。
自定義插件實戰
需求
插件能夠改變或者擴展Mybatis的原有的功能,像Mybatis涉及到分頁操作,通常就會去引用分頁插件來實現分頁功能,所以搞懂插件還是非常有必要的。下面通過一個簡單的自定義插件來實戰一個分片功能,來讓讀者對插件有更深的了解。
實現過程
首先,自定義一個分片路由插件,通過@Intercepts定義插件的攔截的目標類型,當前插件主要攔截StatementHandler類型,對query、update、prepare方法進行攔截
@Intercepts(
{
@Signature(type=StatementHandler.class,method="prepare",args={Connection.class,Integer.class}),
@Signature(type=StatementHandler.class,method="query",args={Statement.class,ResultHandler.class}),
@Signature(type=StatementHandler.class,method="update",args={Statement.class})
}
)
public class MyRoutePlugin implements Interceptor{
@Autowired
private RouteConfig routeConfig;
@Autowired
private DataSource datasouce;
}
同時定義一個分片規則配置類,其中routeKey為分片字段,決定當前執行的SQL語句是否需要分片
@ConfigurationProperties(prefix="route")
@Component
@Data
public class RouteConfg {
private boolean enabled=true;
//分片字段
private String routeKey;
//分片表的數量
private int tableCount;
}
接下來,重寫intercept方法,定義路由插件的實現邏輯,核心邏輯就是根據StatementHandler一步步通過反射拿到當前執行的SQL語句,然后確認是否開啟路由分片,開啟之后就會進行后續分片處理
public Object intercept(Invocation invocation) throws Throwable {
//先判斷攔截的目標類型是否為StatementHandler
if(invocation.getTarget() instanceof StatementHandler){
//獲得具體statementHandler實現,這里拿到的是RoutingStatementHandler
StatementHandler statementHandler=(StatementHandler) invocation.getTarget();
//通過RoutingStatementHandler,反射拿到它內部的屬性delegate,這個delegate就是具體的statementHandler實現
Field delegate= getField(statementHandler,"delegate");
//獲得statementHandler實現
PreparedStatementHandler preparedStatementHandler= (PreparedStatementHandler) delegate.get(statementHandler);
//拿到boundSql
BoundSql boundSql= preparedStatementHandler.getBoundSql();
//拿到它內部sql語句
Field sqlF=getField(boundSql, "sql");
String sql=(String) sqlF.get(boundSql);
if(routeConfig.isEnabled()){
//處理分片
return handlerRoute(sql,boundSql,preparedStatementHandler,invocation,sqlF);
}
}
return invocation.proceed();
}
//獲得實例中指定name的field
public Field getField(Object obj,String fieldName){
Field field=ReflectionUtils.findField(obj.getClass(), fieldName);
//設置訪問權限
ReflectionUtils.makeAccessible(field);
return field;
}
接下來,根據不同的SQL語句類型進行不同分片處理,這里只實現了對查詢和插入的分片
//處理路由分片
private Object handlerRoute(String sql, BoundSql boundSql,
PreparedStatementHandler preparedStatementHandler,Invocation invocation,Field sqlF) throws InvocationTargetException, IllegalAccessException, IllegalArgumentException, SQLException {
//判斷查詢類型
if(sql.contains("select")||sql.contains("SELECT")){
return hanlderSelectRoute(sql,boundSql,preparedStatementHandler,invocation,sqlF);
}
if(sql.contains("insert")||sql.contains("INSERT")){
return handlerInsertRoute(sql,boundSql,preparedStatementHandler,invocation,sqlF);
}
return invocation.proceed();
}
查詢的分片處理流程: 先根據執行的SQL語句獲得舊的表名,接下來判斷是否配置了路由分片字段,如果配置的話,那么會通過當前SQL語句的入參信息,確認SQL語句的查詢參數中是否有包含分片字段。如果查詢參數滿足分片,那么就會根據對應的參數值計算它的hash值,然后基于hash值根據分片表數進行求余,確認分片后的表名,最后通過反射將當前執行的BoundSql中SQL語句替換為新的SQL語句,最終查詢就會基于新的SQL語句進行查詢,實現了分片效果。
//獲得查詢語句的表名
private String getSelectName(String sql) {
String from = sql.substring(sql.indexOf("from") + 4);
String tableName = from.substring(0, from.indexOf("where")).trim();
return tableName;
}
//查詢語句的路由分片
private Object hanlderSelectRoute(String sql, BoundSql boundSql,
PreparedStatementHandler preparedStatementHandler, Invocation invocation, Field sqlF) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SQLException {
//獲得表名
String tableName=getSelectName(sql);
//從boundSql里面的參數映射中,找到是否有按當前路由分配規則進行分片的字段
//分場景
//存在路由分片規則
if(routeConfig.getRouteKey()!=null){
Long hashcode=0L;
List<ParameterMapping> list=boundSql.getParameterMappings();
for(ParameterMapping bean:list){
//判斷查詢的字段是否為分片字段
if(bean.getProperty().equals(routeConfig.getRouteKey())){
hashcode= (long) boundSql.getParameterObject().toString().hashCode();
break;
}
}
if(0!=hashcode){
int tableCount = (int) (hashcode%(long) routeConfig.getTableCount())+1;
tableName=tableName+tableCount;
sqlF.set(boundSql, replaceSelectSql(sql,tableName));
return invocation.proceed();
}
}
//判斷是否是prepare方法
if("prepare".equals(invocation.getMethod().getName())){
//直接向后傳遞
return invocation.proceed();
}
//不按路由分片規則,就需要查所有表來查出數據
List<Object> result=new ArrayList<Object>();
for(int i=1;i<=routeConfig.getTableCount();i++){
//修改它的Statement入參
Statement statement=getStatement(preparedStatementHandler, sqlF, tableName + i, boundSql, sql);
//修改它的入參
invocation.getArgs()[0]=statement;
//調用結果
List<Object> tmp=(List<Object>) invocation.proceed();
if(tmp!=null&&!tmp.isEmpty()){
result.add(tmp);
}
}
return result;
}
//替換查詢語句的表名
private Object replaceSelectSql(String sql, String tableName) {
String from = sql.substring(0, sql.indexOf("from") + 4);
String where = sql.substring(sql.indexOf("where"));
return from + " " + tableName + " " + where;
}
如果當前未配置分片字段或者不滿足分片策略時,此時就需要通過所有表來查數據。要查詢所有分片表的數據,此時需要調用getStatement方法,為每個表的查詢構造一個新的StatementHandler實例,然后再通過新的StatementHandler去查詢分片表的數據,最終將查詢結果匯總到List集合中并返回。
//創建一個新的StatementHandler
private Statement getStatement(StatementHandler preparedStatementHandler, Field sqlF, String tableName,
BoundSql boundSql, String sql) throws IllegalArgumentException, IllegalAccessException, SQLException {
//修改sql語句
sqlF.set(boundSql, replaceSelectSql(sql, tableName));
//先獲得連接對象
Connection connection=DataSourceUtils.getConnection(datasouce);
//獲得statementLog
Log statementLog=getStatementLog(preparedStatementHandler);
//獲得連接日志代理對象
if (statementLog.isDebugEnabled()) {
connection= ConnectionLogger.newInstance(connection, statementLog, 1);
}
//獲得具體StatementHandler
Statement statement=preparedStatementHandler.prepare(connection, null);
//參數設置
preparedStatementHandler.parameterize(statement);
//返回最終具體的statement實例
return statement;
}
private Log getStatementLog(StatementHandler preparedStatementHandler) throws IllegalArgumentException, IllegalAccessException {
Field mp=getField(preparedStatementHandler, "mappedStatement");
//實例化
MappedStatement mappedStatement = (MappedStatement) mp.get(preparedStatementHandler);
return mappedStatement.getStatementLog();
}
插入的分片處理流程,也是類似的,這里就不分析了。
//處理插入的分片
private Object handlerInsertRoute(String sql, BoundSql boundSql,
PreparedStatementHandler preparedStatementHandler, Invocation invocation,Field sqlF) throws InvocationTargetException, IllegalAccessException {
if(routeConfig.getRouteKey()!=null){
Long hashcode=0L;
List<ParameterMapping> list=boundSql.getParameterMappings();
for(ParameterMapping bean:list){
if(bean.getProperty().equals(routeConfig.getRouteKey())){
Field field=ReflectionUtils.findField(boundSql.getParameterObject().getClass(), bean.getProperty());
//設置訪問權限
ReflectionUtils.makeAccessible(field);
hashcode=(long) field.get(boundSql.getParameterObject()).toString().hashCode();
break;
}
}
Long primaryId=hashcode;
int tableCount = (int) (primaryId%(long) routeConfig.getTableCount())+1;
//獲得表名
String tableName=getSqlName(sql);
tableName=tableName+tableCount;
//修改sql
sqlF.set(boundSql, replaceSql(sql,tableName));
}
return invocation.proceed();
}
//獲得新的插入sql語句
private Object replaceSql(String sql,String tableName) {
//前部分
String head=sql.substring(0,sql.indexOf("into")+4);
//后部分
String low=sql.substring(sql.indexOf("values"));
return head+" "+tableName+" "+low;
}
//獲得插入語句的表名
private String getSqlName(String sql) {
String tableName=sql.substring(sql.indexOf("into")+4,sql.indexOf("values"));
if(tableName.contains("(")){
tableName=tableName.substring(0,tableName.indexOf("("));
}
return tableName.trim();
}
測試
定義一個Mapper接口
@Mapper
public interface TUserMapper {
@Select("select user_id as userId,user_name as userName,seqfrom tb_user where user_id = #{userId}")
TbUser selectByPrimaryKey(Integer userId);
@Select("select user_id as userId,user_name as userName,seqfrom tb_user where user_name = #{userName}")
List<TbUser> selectByUserName(String userName);
@Insert("insert into tb_user (user_id,user_name,seq) values(#{userId},#{userName},#{seq})")
void addT_user(TbUser user);
}
數據庫中兩張分片表
配置文件中指定路由分片策略
route.enabled=true
route.routeKey=userId
route.tableCount=2
第一種情況,向先表中插入10條數據
@Test
public void test5() {
Random random = new Random();
for (int i = 1; i < 11; i++) {
TbUser user = new TbUser();
user.setUserId((long)random.nextInt(1000));
user.setUserName("test" + i);
user.setSeq(i);
tuserMapper.addT_user(user);
}
}
從結果可以看到,插入時它會根據userId值進行分片,將數據分別保存到兩張表中
第二種情況,指定userId查詢一條記錄
@Test
public void test7() {
TbUser tbUser = tuserMapper.selectByPrimaryKey(99);
System.out.println("tbUser: "+tbUser.toString());
}
從結果可以看到,根據指定userId的值進行了分片,從tb_user1表查到了數據
第三種情況,不通過分片鍵查詢數據
@Test
public void test7() {
List<TbUser> list=tuserMapper.selectByUserName("test5");
System.out.println("tbUser: "+list.toString());
}
從結果可以看到,查詢了兩個表,匯總了結果,并且從tb_user1表中查到了數據
總結
需要明確一點,上述的分片邏輯不是重點,畢竟真正做分庫分表的還是需要去引用數據庫中間件的。上述示例實現中應該去關注如何一步步進行SQL的改造,以及Mybatis執行過程中一些重要的組件是如何創建的,知道了這些才能對Mybatis有更深的了解。
后續補充一張流程圖(需要源碼工程的,可以在評論區回復)
Spring與Mybatis整合
整合過程
引入mybatis-spring依賴包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
定義Mybatis的配置類,指定要掃描的Mapper接口包路徑,同時指定一個SqlSessionFactoryBean的實例。整合的主要配置就這些,非常簡單,但是我們應該關注這些配置背后做的事情。
@Configuration
@MapperScan(basePackages="com.stu",annotationClass=Mapper.class)
public class MybatisConfig {
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(Driver.class.getName());
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test");
return dataSource;
}
@Bean
public SqlSessionFactoryBean sessionFactoryBean(@Autowired DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
sqlSessionFactory.setDataSource(dataSource);
return sqlSessionFactory;
}
}
實現原理
@MapperScan
首先,從上面的配置類可以看到它定義了一個@MapperScan注解,這個注解目的向Spring容器中注冊了一個Mapper接口的掃描類
@Import(MapperScannerRegistrar.class)
@Repeatable(MapperScans.class)
public @interface MapperScan {
而MapperScan的功能是基于@Import注解定義的屬性類MapperScannerRegistrar完成的,由于它實現了ImportBeanDefinitionRegistrar這個Spring的擴展點,因此當該類被Spring解析后就會觸發執行registerBeanDefinitions這個方法
public class MapperScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware {
...
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
//獲得mapperscan注解的屬性
AnnotationAttributes mapperScanAttrs = AnnotationAttributes
.fromMap(importingClassMetadata.getAnnotationAttributes(MapperScan.class.getName()));
if (mapperScanAttrs != null) {
//向Spring容器中注冊Mybatis的掃描類
registerBeanDefinitions(importingClassMetadata, mapperScanAttrs, registry,
generateBaseBeanName(importingClassMetadata, 0));
}
}
之后又會執行到registerBeanDefinitions這個核心方法,而這個方法就會將Mapper接口的掃描類MapperScannerConfigurer封裝成BeanDefinition對象注冊到Spring容器中,到這里@MapperScan注解的功能就完成了。
//核心: 向Spring注冊mybatis的核心組件
void registerBeanDefinitions(AnnotationMetadata annoMeta, AnnotationAttributes annoAttrs,
BeanDefinitionRegistry registry, String beanName) {
//創建一個類型為MapperScannerConfigurer的BeanDefinition對象
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
builder.addPropertyValue("processPropertyPlaceHolders", true);
//獲得注解類型: annotationClass = Mapper.class;在Repository包下所有的接口都會帶上@Mapper接口
Class<? extends Annotation> annotationClass = annoAttrs.getClass("annotationClass");
if (!Annotation.class.equals(annotationClass)) {
builder.addPropertyValue("annotationClass", annotationClass);
}
...
List<String> basePackages = new ArrayList<>();
basePackages.addAll(
Arrays.stream(annoAttrs.getStringArray("value")).filter(StringUtils::hasText).collect(Collectors.toList()));
basePackages.addAll(Arrays.stream(annoAttrs.getStringArray("basePackages")).filter(StringUtils::hasText)
.collect(Collectors.toList()));
basePackages.addAll(Arrays.stream(annoAttrs.getClassArray("basePackageClasses")).map(ClassUtils::getPackageName)
.collect(Collectors.toList()));
if (basePackages.isEmpty()) {
basePackages.add(getDefaultBasePackage(annoMeta));
}
builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(basePackages));
//注冊
registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
}
}
MapperScannerConfigurer
這個類的是真正實現掃描Mapper接口的,查看這個類的類圖可以發現它實現了BeanDefinitionRegistryPostProcessor這個Spring的擴展點,因此Spring容器啟動過程就會先調用該類的postProcessBeanDefinitionRegistry方法
public class MapperScannerConfigurer
implements BeanDefinitionRegistryPostProcessor, InitializingBean, ApplicationContextAware, BeanNameAware {
....
//核心方法:掃描指定注解的類,封裝成BeanDefinition對象,添加到spring容器中
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
if (this.processPropertyPlaceHolders) {
processPropertyPlaceHolders();
}
//創建一個mapper掃描器
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
scanner.setAddToConfig(this.addToConfig);
scanner.setAnnotationClass(this.annotationClass);//標識掃描的注解類型
scanner.setMarkerInterface(this.markerInterface);
scanner.setSqlSessionFactory(this.sqlSessionFactory);
scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
scanner.setResourceLoader(this.applicationContext);
scanner.setBeanNameGenerator(this.nameGenerator);
scanner.setMapperFactoryBeanClass(this.mapperFactoryBeanClass);
if (StringUtils.hasText(lazyInitialization)) {
scanner.setLazyInitialization(Boolean.valueOf(lazyInitialization));
}
//這里注冊掃描的接口類型
scanner.registerFilters();
//執行掃描
scanner.scan(
StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
}
這個方法中主要創建了一個ClassPathMapperScanner掃描器,而這個掃描器又繼承了Spring的ClassPathBeanDefinitionScanner這個掃描器。在執行scan方法掃描時,會先通過ClassPathBeanDefinitionScanner父類掃描器將配置的basePackages包(Mapper接口)路徑下所有Mapper接口變成BeanDefinition對象注冊到Spring容器中
public Set<BeanDefinitionHolder> doScan(String... basePackages) {
//將basePackages路徑下所有Mapper接口,變成BeanDefinition對象注冊到Spring容器中
Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
if (beanDefinitions.isEmpty()) {
LOGGER.warn(() -> "No MyBatis mapper was found in '" + Arrays.toString(basePackages)
+ "' package. Please check your configuration.");
} else {
//處理掃描得到的beanDefinitionholder集合,將集合中的每一個mapper接口轉換成mapperfactorybean后,注冊到spring容器中
processBeanDefinitions(beanDefinitions);
}
return beanDefinitions;
}
之后當前ClassPathMapperScanner掃描器又會執行到processBeanDefinitions這個方法,對掃描得到的beanDefinitionholder集合進行處理,將集合中的每一個Mapper接口對應的BeanDefinition對象對應的BeanClass替換為mapperFactoryBeanClass,并為當前BeanDefinition對象的構造函數屬性中添加一個以Mapper接口做為入參構造函數(這樣當前BeanDefinition對象被實例化時,就會通過該構造函數進行實例化)。最終每一個掃描的Mapper接口注冊到Spring容器中,都是對應一個類型為MapperFactoryBean的BeanDefinition對象。
private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) {
GenericBeanDefinition definition;
for (BeanDefinitionHolder holder : beanDefinitions) {
definition = (GenericBeanDefinition) holder.getBeanDefinition();
String beanClassName = definition.getBeanClassName();
LOGGER.debug(() -> "Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + beanClassName
+ "' mapperInterface");
// the mapper interface is the original class of the bean
// but, the actual class of the bean is MapperFactoryBean
//增加一個構造方法,接口類型作為構造函數的入參
definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName); // issue #59
//設置當前bean的類型
definition.setBeanClass(this.mapperFactoryBeanClass);
definition.getPropertyValues().add("addToConfig", this.addToConfig);
boolean explicitFactoryUsed = false;
if (StringUtils.hasText(this.sqlSessionFactoryBeanName)) {
definition.getPropertyValues().add("sqlSessionFactory",
new RuntimeBeanReference(this.sqlSessionFactoryBeanName));
explicitFactoryUsed = true;
} else if (this.sqlSessionFactory != null) {
//添加sqlsessionfactory屬性
definition.getPropertyValues().add("sqlSessionFactory", this.sqlSessionFactory);
explicitFactoryUsed = true;
}
....
}
}
MapperFactoryBean
Mapper接口掃描完成后,在應用程序中通過@Autowired注解注入一個Mapper接口時,實際上會注入MapperFactoryBean這個實例,查看MapperFactoryBean類圖可以看到它實現了Spring的FactoryBean接口,因此最終注入的會是getObject()方法返回的實例,getObject()方法做的事情就是通過sqlSession獲得當前Mapper接口的代理對象,因此最終依賴注入的就是一個Mapper接口的代理對象。
public class MapperFactoryBean<T> extends SqlSessionDaoSupport implements FactoryBean<T>{
public T getObject() throws Exception {
//獲得mapper的代理對象
return getSqlSession().getMapper(this.mapperInterface);
}
}
還有一個關鍵點,Mybatis為Mapper接口創建代理對象時,需要先向Mybatis的Configuration配置類中注冊每一個Mapper接口的代理工廠,之后通過代理工廠才能創建Mapper接口代理對象。而代理工廠的創建是在MapperFactoryBean的checkDaoConfig()方法執行的,觸發的時機是由于MapperFactoryBean繼承了SqlSessionDaoSupport,該類又繼承了DaoSupport,而DaoSupport又實現了InitializingBean接口,當MapperFactoryBean實例化過程就會觸發執行afterPropertiesSet方法,然后就會調用到checkDaoConfig()方法,完成為Mapper接口創建代理工廠對象的過程。
/**
* 由于繼承了SqlSessionDaoSupport該類,該類有基礎了DaoSupport,而DaoSupport又實現了InitializingBean接口,會觸發執行afterPropertiesSet,然后會調用到該方法
* 建立接口和代理工廠的映射關系
*/
@Override
protected void checkDaoConfig() {
super.checkDaoConfig();
notNull(this.mapperInterface, "Property 'mapperInterface' is required");
Configuration configuration = getSqlSession().getConfiguration();
if (this.addToConfig && !configuration.hasMapper(this.mapperInterface)) {
try {
//為當前接口添加代理工廠對象
configuration.addMapper(this.mapperInterface);
} catch (Exception e) {
logger.error("Error while adding the mapper '" + this.mapperInterface + "' to configuration.", e);
throw new IllegalArgumentException(e);
} finally {
ErrorContext.instance().reset();
}
}
}
SqlSessionFactoryBean
前面的Mybatis配置類中,可以看到通過@Bean方式注入了一個SqlSessionFactoryBean的實例,而SqlSessionFactoryBean有什么作用呢?查看這個類的類圖可以發現它實現了InitializingBean和FactoryBean兩個接口。實現InitializingBean接口,那么當前bean被實例化過程中,就會調用到afterPropertiesSet方法,而該方法內部主要調用了buildSqlSessionFactory()方法,在這個buildSqlSessionFactory()方法中,目的就是創建Mybatis中SqlSessionFactory的實例。
public void afterPropertiesSet() throws Exception {
Assert.notNull(this.dataSource, "Property 'dataSource' is required");
Assert.notNull(this.sqlSessionFactoryBuilder, "Property 'sqlSessionFactoryBuilder' is required");
this.sqlSessionFactory = this.buildSqlSessionFactory();
}
而實現FactoryBean接口,那么Spring獲取SqlSessionFactoryBean實例時實際上獲得的是getObject方法返回的實例,而getObject方法返回的就是前面創建好的SqlSessionFactory這個實例。通過這兩個接口就完成了SqlSessionFactory的實例化,并注冊到Spring容器中。
public SqlSessionFactory getObject() throws Exception {
if (this.sqlSessionFactory == null) {
this.afterPropertiesSet();
}
return this.sqlSessionFactory;
}
總結
最后上一張簡單時序圖
本文到這里就結束了,感謝看到最后的朋友,都看到最后了,點個贊再走啊,如有不對之處還請多多指正。