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")



结构



数据源
   
   
  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. <project 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. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.unioncast</groupId>
  6. <artifactId>unioncast-db-service</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <packaging>war</packaging>
  9. <name>unioncast-db-service</name>
  10. <description>Demo project for Spring Boot</description>
  11. <parent>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-parent</artifactId>
  14. <version>1.4.1.RELEASE</version>
  15. <relativePath /> <!-- lookup parent from repository -->
  16. </parent>
  17. <repositories>
  18. <repository>
  19. <id>nexus</id>
  20. <name>nexus</name>
  21. <url>http://192.168.101.23:8081/nexus/content/groups/public/</url>
  22. <releases>
  23. <enabled>true</enabled>
  24. </releases>
  25. <snapshots>
  26. <enabled>true</enabled>
  27. </snapshots>
  28. </repository>
  29. </repositories>
  30. <properties>
  31. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  32. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  33. <java.version>1.8</java.version>
  34. </properties>
  35. <dependencies>
  36. <!-- 自己的公共库依赖 -->
  37. <dependency>
  38. <groupId>com.unioncast</groupId>
  39. <artifactId>unioncast-common</artifactId>
  40. <version>0.0.1-SNAPSHOT</version>
  41. <exclusions>
  42. <exclusion>
  43. <groupId>javax.servlet</groupId>
  44. <artifactId>servlet-api</artifactId>
  45. </exclusion>
  46. </exclusions>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework.boot</groupId>
  50. <artifactId>spring-boot-starter-actuator</artifactId>
  51. <exclusions>
  52. <exclusion>
  53. <groupId>org.springframework.boot</groupId>
  54. <artifactId>spring-boot-starter-logging</artifactId>
  55. </exclusion>
  56. </exclusions>
  57. </dependency>
  58. <dependency>
  59. <groupId>org.springframework.boot</groupId>
  60. <artifactId>spring-boot-starter-aop</artifactId>
  61. </dependency>
  62. <dependency>
  63. <groupId>org.springframework.boot</groupId>
  64. <artifactId>spring-boot-actuator-docs</artifactId>
  65. </dependency>
  66. <dependency>
  67. <groupId>org.springframework.boot</groupId>
  68. <artifactId>spring-boot-starter-cache</artifactId>
  69. </dependency>
  70. <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId>
  71. </dependency> -->
  72. <dependency>
  73. <groupId>org.springframework.boot</groupId>
  74. <artifactId>spring-boot-starter-data-rest</artifactId>
  75. </dependency>
  76. <dependency>
  77. <groupId>org.springframework.data</groupId>
  78. <artifactId>spring-data-rest-hal-browser</artifactId>
  79. </dependency>
  80. <dependency>
  81. <groupId>org.springframework.boot</groupId>
  82. <artifactId>spring-boot-devtools</artifactId>
  83. </dependency>
  84. <dependency>
  85. <groupId>org.springframework.boot</groupId>
  86. <artifactId>spring-boot-starter-jdbc</artifactId>
  87. </dependency>
  88. <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId>
  89. </dependency> -->
  90. <dependency>
  91. <groupId>org.springframework.boot</groupId>
  92. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  93. </dependency>
  94. <dependency>
  95. <groupId>org.springframework.boot</groupId>
  96. <artifactId>spring-boot-starter-web</artifactId>
  97. </dependency>
  98. <dependency>
  99. <groupId>com.h2database</groupId>
  100. <artifactId>h2</artifactId>
  101. <scope>runtime</scope>
  102. </dependency>
  103. <dependency>
  104. <groupId>mysql</groupId>
  105. <artifactId>mysql-connector-java</artifactId>
  106. <scope>runtime</scope>
  107. </dependency>
  108. <dependency>
  109. <groupId>org.springframework.boot</groupId>
  110. <artifactId>spring-boot-starter-tomcat</artifactId>
  111. <!--<scope>provided</scope>-->
  112. </dependency>
  113. <dependency>
  114. <groupId>org.springframework.boot</groupId>
  115. <artifactId>spring-boot-starter-test</artifactId>
  116. <scope>test</scope>
  117. </dependency>
  118. <dependency>
  119. <groupId>org.springframework.restdocs</groupId>
  120. <artifactId>spring-restdocs-mockmvc</artifactId>
  121. <scope>test</scope>
  122. </dependency>
  123. <dependency>
  124. <groupId>org.springframework.boot</groupId>
  125. <artifactId>spring-boot-configuration-processor</artifactId>
  126. <optional>true</optional>
  127. </dependency>
  128. <!-- redis相关 -->
  129. <dependency>
  130. <groupId>org.springframework.boot</groupId>
  131. <artifactId>spring-boot-starter-redis</artifactId>
  132. </dependency>
  133. <!-- c3p0连接池 -->
  134. <dependency>
  135. <groupId>com.mchange</groupId>
  136. <artifactId>c3p0</artifactId>
  137. <version>0.9.5.2</version>
  138. </dependency>
  139. <dependency>
  140. <groupId>org.springframework.boot</groupId>
  141. <artifactId>spring-boot-starter-log4j2</artifactId>
  142. </dependency>
  143. <dependency>
  144. <groupId>org.scala-lang</groupId>
  145. <artifactId>scala-library</artifactId>
  146. <version>2.11.0</version>
  147. </dependency>
  148. <dependency>
  149. <groupId>org.springframework.boot</groupId>
  150. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  151. </dependency>
  152. <dependency>
  153. <groupId>com.sun.jna</groupId>
  154. <artifactId>jna</artifactId>
  155. <version>3.0.9</version>
  156. </dependency>
  157. <!-- Swagger -->
  158. <dependency>
  159. <groupId>io.springfox</groupId>
  160. <artifactId>springfox-swagger-ui</artifactId>
  161. <version>2.2.2</version>
  162. </dependency>
  163. <dependency>
  164. <groupId>io.springfox</groupId>
  165. <artifactId>springfox-swagger2</artifactId>
  166. <version>2.2.2</version>
  167. </dependency>
  168. <!-- END Swagger -->
  169. </dependencies>
  170. <build>
  171. <plugins>
  172. <plugin>
  173. <groupId>org.springframework.boot</groupId>
  174. <artifactId>spring-boot-maven-plugin</artifactId>
  175. </plugin>
  176. <plugin>
  177. <artifactId>maven-surefire-plugin</artifactId>
  178. <configuration>
  179. <skipTests>true</skipTests>
  180. </configuration>
  181. </plugin>
  182. <plugin>
  183. <groupId>org.apache.maven.plugins</groupId>
  184. <artifactId>maven-compiler-plugin</artifactId>
  185. <configuration>
  186. <source>1.8</source>
  187. <target>1.8</target>
  188. <encoding>UTF-8</encoding>
  189. <compilerArgument>-Xlint:unchecked</compilerArgument>
  190. </configuration>
  191. </plugin>
  192. </plugins>
  193. </build>
  194. </project>










 



评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值