说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务。我们项目是后者的模式,网上找了很多,大都是根据jpa来做多数据源解决方案,要不就是老的spring多数据源解决方案,还有的是利用aop动态切换,感觉有点小复杂,其实我只是想找一个简单的多数据支持而已,折腾了两个小时整理出来,供大家参考。

废话不多说直接上代码吧

配置文件

pom包就不贴了比较简单该依赖的就依赖,主要是数据库这边的配置:

  1. mybatis.config-locations=classpath:mybatis/mybatis-config.xml
  2. spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver
  3. spring.datasource.test1.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
  4. spring.datasource.test1.username = root
  5. spring.datasource.test1.password = root
  6. spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver
  7. spring.datasource.test2.url = jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8
  8. spring.datasource.test2.username = root
  9. spring.datasource.test2.password = root

一个test1库和一个test2库,其中test1位主库,在使用的过程中必须指定主库,不然会报错。

数据源配置

  1. @Configuration
  2. @MapperScan(basePackages = "com.neo.mapper.test1", sqlSessionTemplateRef = "test1SqlSessionTemplate")
  3. public class DataSource1Config {
  4. @Bean(name = "test1DataSource")
  5. @ConfigurationProperties(prefix = "spring.datasource.test1")
  6. @Primary
  7. public DataSource testDataSource() {
  8. return DataSourceBuilder.create().build();
  9. }
  10. @Bean(name = "test1SqlSessionFactory")
  11. @Primary
  12. public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
  13. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  14. bean.setDataSource(dataSource);
  15. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
  16. return bean.getObject();
  17. }
  18. @Bean(name = "test1TransactionManager")
  19. @Primary
  20. public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
  21. return new DataSourceTransactionManager(dataSource);
  22. }
  23. @Bean(name = "test1SqlSessionTemplate")
  24. @Primary
  25. public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  26. return new SqlSessionTemplate(sqlSessionFactory);
  27. }
  28. }

最关键的地方就是这块了,一层一层注入,首先创建DataSource,然后创建SqlSessionFactory再创建事务,最后包装到SqlSessionTemplate中。其中需要指定分库的mapper文件地址,以及分库dao层代码

  1. @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

  1. public interface User1Mapper {
  2. List<UserEntity> getAll();
  3. UserEntity getOne(Long id);
  4. void insert(UserEntity user);
  5. void update(UserEntity user);
  6. void delete(Long id);
  7. }

xml层

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="com.neo.mapper.test1.User1Mapper" >
  4. <resultMap id="BaseResultMap" type="com.neo.entity.UserEntity" >
  5. <id column="id" property="id" jdbcType="BIGINT" />
  6. <result column="userName" property="userName" jdbcType="VARCHAR" />
  7. <result column="passWord" property="passWord" jdbcType="VARCHAR" />
  8. <result column="user_sex" property="userSex" javaType="com.neo.enums.UserSexEnum"/>
  9. <result column="nick_name" property="nickName" jdbcType="VARCHAR" />
  10. </resultMap>
  11. <sql id="Base_Column_List" >
  12. id, userName, passWord, user_sex, nick_name
  13. </sql>
  14. <select id="getAll" resultMap="BaseResultMap" >
  15. SELECT
  16. <include refid="Base_Column_List" />
  17. FROM users
  18. </select>
  19. <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
  20. SELECT
  21. <include refid="Base_Column_List" />
  22. FROM users
  23. WHERE id = #{id}
  24. </select>
  25. <insert id="insert" parameterType="com.neo.entity.UserEntity" >
  26. INSERT INTO
  27. users
  28. (userName,passWord,user_sex)
  29. VALUES
  30. (#{userName}, #{passWord}, #{userSex})
  31. </insert>
  32. <update id="update" parameterType="com.neo.entity.UserEntity" >
  33. UPDATE
  34. users
  35. SET
  36. <if test="userName != null">userName = #{userName},</if>
  37. <if test="passWord != null">passWord = #{passWord},</if>
  38. nick_name = #{nickName}
  39. WHERE
  40. id = #{id}
  41. </update>
  42. <delete id="delete" parameterType="java.lang.Long" >
  43. DELETE FROM
  44. users
  45. WHERE
  46. id =#{id}
  47. </delete>
  48. </mapper>

测试

测试可以使用SpringBootTest,也可以放到Controller中,这里只贴Controller层的使用

  1. @RestController
  2. public class UserController {
  3. @Autowired
  4. private User1Mapper user1Mapper;
  5. @Autowired
  6. private User2Mapper user2Mapper;
  7. @RequestMapping("/getUsers")
  8. public List<UserEntity> getUsers() {
  9. List<UserEntity> users=user1Mapper.getAll();
  10. return users;
  11. }
  12. @RequestMapping("/getUser")
  13. public UserEntity getUser(Long id) {
  14. UserEntity user=user2Mapper.getOne(id);
  15. return user;
  16. }
  17. @RequestMapping("/add")
  18. public void save(UserEntity user) {
  19. user2Mapper.insert(user);
  20. }
  21. @RequestMapping(value="update")
  22. public void update(UserEntity user) {
  23. user2Mapper.update(user);
  24. }
  25. @RequestMapping(value="/delete/{id}")
  26. public void delete(@PathVariable("id") Long id) {
  27. user1Mapper.delete(id);
  28. }
  29. }