日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

springboot(七):springboot+mybatis多数据源最简解决方案

發布時間:2025/3/18 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 springboot(七):springboot+mybatis多数据源最简解决方案 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

為什么80%的碼農都做不了架構師?>>> ??

說起多數據源,一般都來解決那些問題呢,主從模式或者業務比較復雜需要連接不同的分庫來支持業務。我們項目是后者的模式,網上找了很多,大都是根據jpa來做多數據源解決方案,要不就是老的spring多數據源解決方案,還有的是利用aop動態切換,感覺有點小復雜,其實我只是想找一個簡單的多數據支持而已,折騰了兩個小時整理出來,供大家參考。

廢話不多說直接上代碼吧

配置文件

pom包就不貼了比較簡單該依賴的就依賴,主要是數據庫這邊的配置:

mybatis.config-locations=classpath:mybatis/mybatis-config.xmlspring.datasource.test1.driverClassName = com.mysql.jdbc.Driver spring.datasource.test1.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8 spring.datasource.test1.username = root spring.datasource.test1.password = rootspring.datasource.test2.driverClassName = com.mysql.jdbc.Driver spring.datasource.test2.url = jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8 spring.datasource.test2.username = root spring.datasource.test2.password = root

一個test1庫和一個test2庫,其中test1位主庫,在使用的過程中必須制定主庫,不然會報錯。

數據源配置

@Configuration @MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate") public class DataSource1Config {@Bean(name = "test1DataSource")@ConfigurationProperties(prefix = "spring.datasource.test1")@Primarypublic DataSource testDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "test1SqlSessionFactory")@Primarypublic SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));return bean.getObject();}@Bean(name = "test1TransactionManager")@Primarypublic DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Bean(name = "test1SqlSessionTemplate")@Primarypublic SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(sqlSessionFactory);}}

最關鍵的地方就是這塊了,一層一層注入,先創建DataSource,在創建SqlSessionFactory在創建事務,最后包裝到SqlSessionTemplate中。其中需要制定分庫的mapper文件地址,以及分庫到層代碼

@MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")

這塊的注解就是指明了掃描dao層,并且給dao層注入指定的SqlSessionTemplate。所有@Bean都需要按照命名指定正確。

dao層和xml層

dao層和xml需要按照庫來分在不同的目錄,比如:test1庫dao層在com.neo.mapper.test1包下,test2庫在com.neo.mapper.test1

public interface User1Mapper {List<UserEntity> getAll();UserEntity getOne(Long id);void insert(UserEntity user);void update(UserEntity user);void delete(Long id);}

xml層

<?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="com.neo.mapper.test1.User1Mapper" ><resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" ><id column="id" property="id" jdbcType="BIGINT" /><result column="userName" property="userName" jdbcType="VARCHAR" /><result column="passWord" property="passWord" jdbcType="VARCHAR" /><result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/><result column="nick_name" property="nickName" jdbcType="VARCHAR" /></resultMap><sql id="Base_Column_List" >id, userName, passWord, user_sex, nick_name</sql><select id="getAll" resultMap="BaseResultMap" >SELECT <include refid="Base_Column_List" />FROM users</select><select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >SELECT <include refid="Base_Column_List" />FROM usersWHERE id = #{id}</select><insert id="insert" parameterType="com.neo.entity.UserEntity" >INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})</insert><update id="update" parameterType="com.neo.entity.UserEntity" >UPDATE users SET <if test="userName != null">userName = #{userName},</if><if test="passWord != null">passWord = #{passWord},</if>nick_name = #{nickName}WHERE id = #{id}</update><delete id="delete" parameterType="java.lang.Long" >DELETE FROMusers WHERE id =#{id}</delete></mapper>

測試

測試可以使用SpringBootTest,也可以放到Controller中,這里只貼Controller層的使用

@RestController public class UserController {@Autowiredprivate User1Mapper user1Mapper;@Autowiredprivate User2Mapper user2Mapper;@RequestMapping("/getUsers")public List<UserEntity> getUsers() {List<UserEntity> users=user1Mapper.getAll();return users;}@RequestMapping("/getUser")public UserEntity getUser(Long id) {UserEntity user=user2Mapper.getOne(id);return user;}@RequestMapping("/add")public void save(UserEntity user) {user2Mapper.insert(user);}@RequestMapping(value="update")public void update(UserEntity user) {user2Mapper.update(user);}@RequestMapping(value="/delete/{id}")public void delete(@PathVariable("id") Long id) {user1Mapper.delete(id);}}

示例代碼

作者:純潔的微笑
出處:http://www.ityouknow.com/?
版權所有,歡迎保留原文鏈接進行轉載:)

轉載于:https://my.oschina.net/cnarthurs/blog/1519609

總結

以上是生活随笔為你收集整理的springboot(七):springboot+mybatis多数据源最简解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。