如何用Mybatis分库分表
分庫
在分庫的時候 有時候為了方便 一些表需要存放所有庫的信息,稱為全局庫。如:用戶表存放所有的用戶。
此時分庫的思路 數據庫分為全局庫和業務庫,其中業務庫又分為N多個庫,全局庫只放個別表方便開發。
這個時候 就需要一個全局DAO,此時我們的Mybatis就需要支持兩個DAO
兩個DAO(bizDao和globalDao)就需要有兩個sqlSessionFactory,bizSqlSessionFactory和globalSqlSessionFactory和兩個事物管理器transactionManager
<bean id="bizDao" class="com.xxx.dao.BizDao"><property name="sqlSessionFactory" ref="bizSqlSessionFactory"/></bean><bean id="globalDao" class="com.xxx.dao.GlobalDao"><property name="sqlSessionFactory" ref="globalSqlSessionFactory"/></bean> <bean id="bizSqlSessionFactory" parent="sqlSessionFactoryDefault" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="routingDataSource"/> </bean><bean id="globalSqlSessionFactory" parent="sqlSessionFactoryDefault" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="globalDataSource"/> </bean>根據請求動態指定業務庫DataSource
分庫就是一個項目有多個數據庫,對Myabtis來說就有多個數據源(dataSource)根據你的請求 判斷應該查詢哪個庫 從而指定動態指定哪個數據源
可以繼承Spring的AbstractRoutingDataSource重寫接口中determineCurrentLookupKey()根據業務需求返回當前的dbkey(哪個庫1、2、3、4。。。)
全局庫和業務庫事物管理器
因為事物是基于Service的,所以Service也建議分為全局Service和業務Service,根據Service類型(建議配個AOP全局處理 放到ThreadLocal中)
實現PlatformTransactionManager接口,接口中getTransaction()方法可以動態的返回指定的事物管理器(從上面的ThreadLocal中拿到當前的事物管理器)
思考:為什么AbstractRoutingDataSource中多個DataSource不需要動態配置事物管理器?
總結:業務庫和全局庫有兩個不同的DataSource,其中業務庫的DataSource繼承Spring的AbstractRoutingDataSource,
Spring又分為了N個DataSource(對bizSqlSessionFactory而言 只有一個RoutingDataSource,RoutingDataSource里面有一個數據源集合)
全局的globalSqlSessionFactory也可以當bizSqlSessionFactory中的AbstractRoutingDataSource的一個屬性 這么做雖然減少了配置,但是開發不直觀。
分表
上面的分庫的思路就是動態指定DateSource和TransactionManager
分表:就是在Mybatis中寫一個攔截器 動態的更改表名
1.攔截器
SqlSessionFactoryBean里面有個private Interceptor[] plugins;屬性 可以配置一些攔截器
我們自己定義的攔截器需要實現Interceptor接口
接口需要加以下注解
@Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class}) })
2.在攔截器里面 我們需要動態解析SQL和更改SQL
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class}) }) public class MybatisInterceptor implements Interceptor {@Overridepublic Object intercept(Invocation invocation) throws Throwable {if (invocation.getTarget() instanceof StatementHandler) {RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();//通過反射拿到statement對象StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");BoundSql boundSql = delegate.getBoundSql();String sql = boundSql.getSql();String pageSql =sql+" limit 1 ";//操作sql//再通過反射把新sql設置進去ReflectUtil.setFieldValue(boundSql, "sql", pageSql);}return invocation.proceed();}Mybatis四大對象以及插件原理
轉載于:https://www.cnblogs.com/ssskkk/p/11109597.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的如何用Mybatis分库分表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如果reporting server出现
- 下一篇: 个人代码库の自定义后缀名