spring mybatis讀寫分離

2021-09-02 21:29:45 字數 2731 閱讀 8749

一、配置定義資料庫連線屬性

二、定義bean

三、事務定義

四、配置外掛程式

五、編寫動態資料來源類

public class dynamicdatasource extends abstractroutingdatasource

setdefaulttargetdatasource(writedatasource);

maptargetdatasources = new hashmap<>();

targetdatasources.put(dynamicdatasourceglobal.write.name(), writedatasource);

if (readdatasources != null)

readdatasourcesize = readdatasources.size();

} else

settargetdatasources(targetdatasources);

super.afterpropertiesset();

}@override

protected object determinecurrentlookupkey()

dynamicdatasourceglobal dynamicdatasourceglobal = dynamicdatasourceholder.getdatasource();

if (dynamicdatasourceglobal == null || dynamicdatasourceglobal == dynamicdatasourceglobal.write || readdatasourcesize <= 0)

//index表示選擇第幾個從資料庫

int index;

if(readdatasourcepollpattern == 1)

} finally

}index = (int) (currvalue % readdatasourcesize);

} else

return dynamicdatasourceglobal.name() + index;

}public void setwritedatasource(object writedatasource)

public listgetreaddatasources()

public void setreaddatasources(listreaddatasources)

public object getwritedatasource()

public int getreaddatasourcesize()

public void setreaddatasourcesize(int readdatasourcesize)

public int getreaddatasourcepollpattern()

public void setreaddatasourcepollpattern(int readdatasourcepollpattern)

public boolean isonlywrite()

public void setonlywrite(boolean onlywrite)

}public class dynamicdatasourceholder

public static void putdatasource(dynamicdatasourceglobal datasource)

public static dynamicdatasourceglobal getdatasource()

public static void cleardatasource()

}public class dynamicdatasourcetransactionmanager extends datasourcetransactionmanager else

super.dobegin(transaction, definition);

}/**

* 清理本地執行緒的資料來源

** @param transaction

*/@override

protected void docleanupaftercompletion(object transaction)

}/**

* desc: mybatis動態資料庫切換外掛程式

*/@intercepts()})

public class dynamicplugin implements interceptor else else

}} else

logger.warn("設定方法[{}] use [{}] strategy, sqlcommandtype [{}]..", ms.getid(), dynamicdatasourceglobal.name(), ms.getsqlcommandtype().name());

cachemap.put(ms.getid(), dynamicdatasourceglobal);

}dynamicdatasourceholder.putdatasource(dynamicdatasourceglobal);

}return invocation.proceed();

}@override

public object plugin(object target) else

}@override

public void setproperties(properties properties)

spring mybatis連線access資料庫

1.所需jar包 spring mybatis common dhcp 版本1.4以上,1.4以下無法支援connectionproperties屬性 注意事項 連線access資料庫前請關閉log4j,log4j的控制台sql日誌輸出會導致 not data sqlexception 2.pom....

spring mybatis事務不回滾

對spring,mybatis進行整合時發現事務不能進行回滾處理,上網查了很多資料依舊還沒解釋,很多都是說要丟擲乙個runtimeexception才能回滾的,但嘗試過多種還不能,如下 classpath jdbc.properties bolgservice bolgflowservice 檢視資...

Spring Mybatis 增刪改查

select from student where id insert into student name,code values delete from student where code update student set name where code select id,name,cod...