SpringBoot多数据源的配置(SpringBoot+MyBatis)

遇到的问题
1,@Primary注解是必要的,不然会出现异常.
      
      
      
      
  1. org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] is defined: expected single matching bean but found 2: test1DataSource,test2DataSource
2,因为存在多个DataSource,SqlSessionFactory,PlatformTransactionManager,SqlSessionTemplate所以要使用"name"来区分.
3,SqlSessionTemplate如果不配置,在访问主数据源的数据没有问题,但是访问另一个数据源就会出现异常.
      
      
      
      
  1. org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): cn.zz.mapper1.UserMapper1.findAll
4,MyBatis@Configuration上需要加注解
@MapperScan(basePackages = "cn.zz.mapper1", sqlSessionTemplateRef  = "test2SqlSessionTemplate")



结构
SpringBoot多数据源的配置(SpringBoot+MyBatis)_第1张图片


数据源
     
     
     
     
  1. package cn.zz.config;
  2. import org.apache.ibatis.session.SqlSessionFactory;
  3. import org.mybatis.spring.SqlSessionFactoryBean;
  4. import org.mybatis.spring.SqlSessionTemplate;
  5. import org.mybatis.spring.annotation.MapperScan;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
  8. import org.springframework.boot.context.properties.ConfigurationProperties;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.context.annotation.Primary;
  12. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  13. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  14. import org.springframework.transaction.PlatformTransactionManager;
  15. import javax.sql.DataSource;
  16. @Configuration
  17. @MapperScan(basePackages = "cn.zz.mapper", sqlSessionTemplateRef = "test1SqlSessionTemplate")
  18. public class DataSource1 {
  19. @Bean(name = "test1DataSource")
  20. @ConfigurationProperties(prefix = "spring.datasource.primary")
  21. @Primary
  22. public DataSource testDataSource() {
  23. return DataSourceBuilder.create().build();
  24. }
  25. @Bean(name = "test1SqlSessionFactory")
  26. @Primary
  27. public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
  28. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  29. bean.setDataSource(dataSource);
  30. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml"));
  31. return bean.getObject();
  32. }
  33. @Bean(name = "test1TransactionManager")
  34. @Primary
  35. public PlatformTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
  36. return new DataSourceTransactionManager(dataSource);
  37. }
  38. @Bean(name = "test1SqlSessionTemplate")
  39. @Primary
  40. public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  41. return new SqlSessionTemplate(sqlSessionFactory);
  42. }
  43. }

      
      
      
      
  1. package cn.zz.config;
  2. import org.apache.ibatis.session.SqlSessionFactory;
  3. import org.mybatis.spring.SqlSessionFactoryBean;
  4. import org.mybatis.spring.SqlSessionTemplate;
  5. import org.mybatis.spring.annotation.MapperScan;
  6. import org.springframework.beans.factory.annotation.Qualifier;
  7. import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
  8. import org.springframework.boot.context.properties.ConfigurationProperties;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
  12. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
  13. import org.springframework.transaction.PlatformTransactionManager;
  14. import javax.sql.DataSource;
  15. @Configuration
  16. @MapperScan(basePackages = "cn.zz.mapper1", sqlSessionTemplateRef = "test2SqlSessionTemplate")
  17. public class DataSource2 {
  18. @Bean(name = "test2DataSource")
  19. @ConfigurationProperties(prefix = "spring.datasource.secondary")
  20. public DataSource testDataSource() {
  21. return DataSourceBuilder.create().build();
  22. }
  23. @Bean(name = "test2SqlSessionFactory")
  24. public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
  25. SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
  26. bean.setDataSource(dataSource);
  27. bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis1/*.xml"));
  28. return bean.getObject();
  29. }
  30. @Bean(name = "test2TransactionManager")
  31. public PlatformTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
  32. return new DataSourceTransactionManager(dataSource);
  33. }
  34. @Bean(name = "test2SqlSessionTemplate")
  35. public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
  36. return new SqlSessionTemplate(sqlSessionFactory);
  37. }
  38. }

Controller
       
       
       
       
  1. package cn.zz.controller;
  2. import cn.zz.model.User;
  3. import cn.zz.service.UserService;
  4. import cn.zz.service1.UserService1;
  5. import org.apache.log4j.Logger;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import java.util.List;
  11. @Controller
  12. public class UserController {
  13. private Logger logger = Logger.getLogger(UserController.class);
  14. @Autowired
  15. private UserService userService;
  16. @Autowired
  17. private UserService1 userService1;
  18. @RequestMapping("/save")
  19. @ResponseBody
  20. public User save() {
  21. User user = userService.save("zz",27,"72");
  22. return user;
  23. }
  24. @RequestMapping("/save1")
  25. @ResponseBody
  26. public String save1() {
  27. userService.save1("zz",27,"72");
  28. return "ok";
  29. }
  30. @RequestMapping("/getUserInfo")
  31. @ResponseBody
  32. public User getUserInfo() {
  33. User user = userService.getUserInfo();
  34. if(user!=null){
  35. System.out.println("user.getName():"+user.getName());
  36. logger.info("user.getAge():"+user.getAge());
  37. }
  38. return user;
  39. }
  40. @RequestMapping("/findAll")
  41. @ResponseBody
  42. public List<User> findAll() {
  43. List<User> user = userService.findAll();
  44. return user;
  45. }
  46. @RequestMapping("/findAll1")
  47. @ResponseBody
  48. public List<User> findAll1() {
  49. List<User> user = userService1.findAll1();
  50. return user;
  51. }
  52. }

Service
        
        
        
        
  1. package cn.zz.service;
  2. import cn.zz.mapper.UserMapper;
  3. import cn.zz.model.User;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.transaction.annotation.Transactional;
  7. import java.util.List;
  8. @Service
  9. @Transactional
  10. public class UserService {
  11. @Autowired
  12. private UserMapper userMapper;
  13. public User getUserInfo(){
  14. User user=userMapper.findUserInfo();
  15. //User user=null;
  16. return user;
  17. }
  18. public User save(String name, Integer age, String password) {
  19. User user=new User();
  20. user.setName(name);
  21. user.setAge(age);
  22. user.setPassword(password);
  23. userMapper.save(user);
  24. return user;
  25. }
  26. public List<User> findAll() {
  27. List<User> user=userMapper.findAll();
  28. //User user=null;
  29. return user;
  30. }
  31. public void save1(String zz, int i, String s) {
  32. User user=new User();
  33. user.setName(zz);
  34. user.setAge(i);
  35. user.setPassword(s);
  36. userMapper.save1(user);
  37. }
  38. }

        
        
        
        
  1. package cn.zz.service1;
  2. import cn.zz.mapper1.UserMapper1;
  3. import cn.zz.model.User;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.transaction.annotation.Transactional;
  7. import java.util.List;
  8. @Service
  9. @Transactional
  10. public class UserService1 {
  11. @Autowired
  12. private UserMapper1 userMapper1;
  13. public List<User> findAll1() {
  14. List<User> user = userMapper1.findAll();
  15. //User user=null;
  16. return user;
  17. }
  18. }

Mapper
         
         
         
         
  1. package cn.zz.mapper;
  2. import cn.zz.model.User;
  3. import java.util.List;
  4. /**
  5. * Created by zl on 2015/8/27.
  6. */
  7. //@Repository(value = "sqlSessionFactoryBean1")
  8. public interface UserMapper {
  9. public User findUserInfo();
  10. void save(User user);
  11. List<User> findAll();
  12. void save1(User user);
  13. }

          
          
          
          
  1. package cn.zz.mapper1;
  2. import cn.zz.model.User;
  3. import java.util.List;
  4. public interface UserMapper1 {
  5. public User findUserInfo();
  6. void save(User user);
  7. List<User> findAll();
  8. void save1(User user);
  9. }

Mapper.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="cn.zz.mapper.UserMapper">
  4. <select id="findUserInfo" resultType="cn.zz.model.User">
  5. select id,name,age,password from user;
  6. select>
  7. <select id="findAll" resultType="cn.zz.model.User">
  8. select id,name,age,password from user;
  9. select>
  10. <insert id="save"
  11. keyProperty="id" keyColumn="id" useGeneratedKeys="true">
  12. INSERT INTO user(name,age,password) VALUES(#{name}, #{age}, #{password});
  13. insert>
  14. <insert id="save1">
  15. INSERT INTO user(name,age,password) VALUES(#{name}, #{age}, #{password});
  16. insert>
  17. mapper>

            
            
            
            
  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="cn.zz.mapper1.UserMapper1">
  4. <select id="findUserInfo" resultType="cn.zz.model.User">
  5. select id,name,age,password from user;
  6. select>
  7. <select id="findAll" resultType="cn.zz.model.User">
  8. select id,name,age,password from user;
  9. select>
  10. <insert id="save"
  11. keyProperty="id" keyColumn="id" useGeneratedKeys="true">
  12. INSERT INTO user(name,age,password) VALUES(#{name}, #{age}, #{password});
  13. insert>
  14. <insert id="save1">
  15. INSERT INTO user(name,age,password) VALUES(#{name}, #{age}, #{password});
  16. insert>
  17. mapper>

实体类
             
             
             
             
  1. package cn.zz.model;
  2. public class User {
  3. private Integer id;
  4. private String name;
  5. private Integer age;
  6. private String password;
  7. public Integer getId() {
  8. return id;
  9. }
  10. public void setId(Integer id) {
  11. this.id = id;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. public Integer getAge() {
  20. return age;
  21. }
  22. public void setAge(Integer age) {
  23. this.age = age;
  24. }
  25. public String getPassword() {
  26. return password;
  27. }
  28. public void setPassword(String password) {
  29. this.password = password;
  30. }
  31. }


application.properties
              
              
              
              
  1. spring.datasource.primary.url=jdbc:mysql://127.0.0.1:3306/zz?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
  2. spring.datasource.primary.username=root
  3. spring.datasource.primary.password=123456
  4. spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver
  5. spring.datasource.secondary.url=jdbc:mysql://127.0.0.1:3306/zz1?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
  6. spring.datasource.secondary.username=root
  7. spring.datasource.secondary.password=123456
  8. spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver

Application
               
               
               
               
  1. package cn.zz;
  2. import org.apache.log4j.Logger;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. //@EnableAutoConfiguration
  6. @SpringBootApplication
  7. //@ComponentScan
  8. //@MapperScan("cn.no7player.mapper")
  9. public class Application {
  10. private static Logger logger = Logger.getLogger(Application.class);
  11. /**
  12. * Start
  13. */
  14. public static void main(String[] args) {
  15. SpringApplication.run(Application.class, args);
  16. logger.info("SpringBoot Start Success");
  17. }
  18. }


pom.xml
             
             
             
             
  1. xml version="1.0" encoding="UTF-8"?>
  2. xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. 4.0.0
  5. com.unioncast
  6. unioncast-db-service
  7. 0.0.1-SNAPSHOT
  8. war
  9. unioncast-db-service
  10. Demo project for Spring Boot
  11. org.springframework.boot
  12. spring-boot-starter-parent
  13. 1.4.1.RELEASE
  14. />
  15. nexus
  16. nexus
  17. http://192.168.101.23:8081/nexus/content/groups/public/
  18. true
  19. true
  20. UTF-8
  21. UTF-8
  22. 1.8
  23. com.unioncast
  24. unioncast-common
  25. 0.0.1-SNAPSHOT
  26. javax.servlet
  27. servlet-api
  28. org.springframework.boot
  29. spring-boot-starter-actuator
  30. org.springframework.boot
  31. spring-boot-starter-logging
  32. org.springframework.boot
  33. spring-boot-starter-aop
  34. org.springframework.boot
  35. spring-boot-actuator-docs
  36. org.springframework.boot
  37. spring-boot-starter-cache
  38. org.springframework.boot
  39. spring-boot-starter-data-rest
  40. org.springframework.data
  41. spring-data-rest-hal-browser
  42. org.springframework.boot
  43. spring-boot-devtools
  44. org.springframework.boot
  45. spring-boot-starter-jdbc
  46. org.springframework.boot
  47. spring-boot-starter-thymeleaf
  48. org.springframework.boot
  49. spring-boot-starter-web
  50. com.h2database
  51. h2
  52. runtime
  53. mysql
  54. mysql-connector-java
  55. runtime
  56. org.springframework.boot
  57. spring-boot-starter-tomcat
  58. org.springframework.boot
  59. spring-boot-starter-test
  60. test
  61. org.springframework.restdocs
  62. spring-restdocs-mockmvc
  63. test
  64. org.springframework.boot
  65. spring-boot-configuration-processor
  66. true
  67. org.springframework.boot
  68. spring-boot-starter-redis
  69. com.mchange
  70. c3p0
  71. 0.9.5.2
  72. org.springframework.boot
  73. spring-boot-starter-log4j2
  74. org.scala-lang
  75. scala-library
  76. 2.11.0
  77. org.springframework.boot
  78. spring-boot-starter-data-elasticsearch
  79. com.sun.jna
  80. jna
  81. 3.0.9
  82. io.springfox
  83. springfox-swagger-ui
  84. 2.2.2
  85. io.springfox
  86. springfox-swagger2
  87. 2.2.2
  88. org.springframework.boot
  89. spring-boot-maven-plugin
  90. maven-surefire-plugin
  91. true
  92. org.apache.maven.plugins
  93. maven-compiler-plugin
  94. 1.8
  95. 1.8
  96. UTF-8
  97. -Xlint:unchecked










 



你可能感兴趣的:(SpringBoot多数据源的配置(SpringBoot+MyBatis))