分享

Spring boot Mybatis(讀寫分離配置)

 用勿龍潛 2016-09-01
2016-07-24 01:08 by 沧海一滴, 132 阅读, 0 评论, 收藏编辑

最近刚接触Spring boot,正是因为他的及简配置方便开发,促使我下定决心要用它把之前写的项目重构,那么问题来了,spring boot怎么整合mybatis呢,下面几个配置类来搞定。

在我的代码当中是实现了数据库读写分离的,所以代码仅做参考,如有需要可以加我微信:benyzhous

【后续更新】

 

1、文件结构

 

 

 

DataBaseConfiguration.java用来获取数据库连接配置信息,配置从application.properties中读取

 

MybatisConfiguration.java也就是MyBatis配置核心入口,构建连接创建SqlSessionFactory

2、下面直接贴代码,有问题的话可以留言或者加我的微信公众号:cha-baba,或者个人微信号:benyzhous

application.yml 相关配置

 

  1. # Server settings  
  2. server:  
  3.     port:8080  
  4.     address:localhost  
  5.   
  6. # DATASOURCE  
  7. jdbc:  
  8.     driverClass: com.mysql.jdbc.Driver  
  9.     url: jdbc:mysql://127.0.0.1:3306/local-kaishustory?useUnicode=true&characterEncoding=utf-8  
  10.     username: root  
  11.     password: root  
  12.   
  13. # SPRING PROFILES  
  14. spring:         
  15.     # HTTP ENCODING  
  16.     http:  
  17.         encoding.charset: UTF-8  
  18.         encoding.enable: true  
  19.         encoding.force: true  
  20.           
  21. # WeiXin Configuration  
  22. weixin:  
  23.     mp:  
  24.        appid: xx  
  25.        secret: ee  
  26.        token: weixin  
  27.        aeskey:  
  28.   
  29. # MyBatis  
  30. mybatis:  
  31.     typeAliasesPackage: com.modou.**.domain  
  32.     mapperLocations: classpath:/com/modou/**/mapper/*.xml  
  33.     configLocation: classpath:/mybatis-config.xml  
  34.   
  35. # LOGGING  
  36. logging:  
  37.     level:  
  38.        com.ibatis:DEBUG  

 

DataBaseConfiguration.java

 

  1. package com.modou.conf.mybatis;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import javax.sql.DataSource;  
  7.   
  8. import org.slf4j.Logger;  
  9. import org.slf4j.LoggerFactory;  
  10. import org.springframework.boot.bind.RelaxedPropertyResolver;  
  11. import org.springframework.context.EnvironmentAware;  
  12. import org.springframework.context.annotation.Bean;  
  13. import org.springframework.context.annotation.Configuration;  
  14. import org.springframework.context.annotation.Primary;  
  15. import org.springframework.core.env.Environment;  
  16. import org.springframework.transaction.annotation.EnableTransactionManagement;  
  17.   
  18. import com.alibaba.druid.pool.DruidDataSource;  
  19.   
  20. @Configuration  
  21. @EnableTransactionManagement  
  22. public class DataBaseConfiguration implements EnvironmentAware {  
  23.   
  24.     private RelaxedPropertyResolver propertyResolver;  
  25.   
  26.     private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class);  
  27.       
  28.     @Override  
  29.     public void setEnvironment(Environment env) {  
  30.         this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");  
  31.     }  
  32.   
  33.     @Bean(name="writeDataSource", destroyMethod = "close", initMethod="init")  
  34.     @Primary  
  35.     public DataSource writeDataSource() {  
  36.         log.debug("Configruing Write DataSource");  
  37.           
  38.         DruidDataSource datasource = new DruidDataSource();  
  39.         datasource.setUrl(propertyResolver.getProperty("url"));  
  40.         datasource.setDriverClassName(propertyResolver.getProperty("driverClassName"));  
  41.         datasource.setUsername(propertyResolver.getProperty("username"));  
  42.         datasource.setPassword(propertyResolver.getProperty("password"));  
  43.           
  44.         return datasource;  
  45.     }  
  46.       
  47.     @Bean(name="readOneDataSource", destroyMethod = "close", initMethod="init")  
  48.     public DataSource readOneDataSource() {  
  49.         log.debug("Configruing Read One DataSource");  
  50.           
  51.         DruidDataSource datasource = new DruidDataSource();  
  52.         datasource.setUrl(propertyResolver.getProperty("url"));  
  53.         datasource.setDriverClassName(propertyResolver.getProperty("driverClassName"));  
  54.         datasource.setUsername(propertyResolver.getProperty("username"));  
  55.         datasource.setPassword(propertyResolver.getProperty("password"));  
  56.           
  57.         return datasource;  
  58.     }  
  59.       
  60.     @Bean(name="readTowDataSource", destroyMethod = "close", initMethod="init")  
  61.     public DataSource readTowDataSource() {  
  62.         log.debug("Configruing Read Two DataSource");  
  63.           
  64.         DruidDataSource datasource = new DruidDataSource();  
  65.         datasource.setUrl(propertyResolver.getProperty("url"));  
  66.         datasource.setDriverClassName(propertyResolver.getProperty("driverClassName"));  
  67.         datasource.setUsername(propertyResolver.getProperty("username"));  
  68.         datasource.setPassword(propertyResolver.getProperty("password"));  
  69.           
  70.         return datasource;  
  71.     }  
  72.       
  73.       
  74.     @Bean(name="readDataSources")  
  75.     public List<DataSource> readDataSources(){  
  76.         List<DataSource> dataSources = new ArrayList<DataSource>();  
  77.         dataSources.add(readOneDataSource());  
  78.         dataSources.add(readTowDataSource());  
  79.         return dataSources;  
  80.     }  
  81.       
  82. }  



 

 

 

MyBatisConfiguration.java

 

  1. package com.modou.conf.mybatis;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.annotation.Resource;  
  6. import javax.persistence.EntityManager;  
  7. import javax.sql.DataSource;  
  8.   
  9. import org.apache.commons.logging.Log;  
  10. import org.apache.commons.logging.LogFactory;  
  11. import org.apache.ibatis.session.SqlSessionFactory;  
  12. import org.mybatis.spring.SqlSessionFactoryBean;  
  13. import org.mybatis.spring.annotation.MapperScan;  
  14. import org.mybatis.spring.plugin.rw.RoundRobinRWRoutingDataSourceProxy;  
  15. import org.springframework.boot.autoconfigure.AutoConfigureAfter;  
  16. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;  
  17. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;  
  18. import org.springframework.boot.bind.RelaxedPropertyResolver;  
  19. import org.springframework.context.EnvironmentAware;  
  20. import org.springframework.context.annotation.Bean;  
  21. import org.springframework.context.annotation.Configuration;  
  22. import org.springframework.core.env.Environment;  
  23. import org.springframework.core.io.DefaultResourceLoader;  
  24. import org.springframework.core.io.support.PathMatchingResourcePatternResolver;  
  25. import org.springframework.jdbc.datasource.DataSourceTransactionManager;  
  26. import org.springframework.transaction.annotation.EnableTransactionManagement;  
  27.   
  28. /** 
  29.  *  
  30.  * 获取第二个数据库的连接信息,在application.yml中配置,并指定特定的前缀 
  31.  *  
  32.  */  
  33. @Configuration  
  34. @ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class })  
  35. @AutoConfigureAfter({ DataBaseConfiguration.class })  
  36. @MapperScan(basePackages={"com.modou.**.mapper","com.github.abel533.entity.mapper"})  
  37. public class MybatisConfiguration implements EnvironmentAware{  
  38.     private static Log logger = LogFactory.getLog(MybatisConfiguration.class);  
  39.   
  40.     private RelaxedPropertyResolver propertyResolver;  
  41.       
  42.     @Resource(name="writeDataSource")  
  43.     private DataSource writeDataSource;  
  44.       
  45.     @Resource(name="readDataSources")  
  46.     private List<Object> readDataSources;  
  47.       
  48.     @Override  
  49.     public void setEnvironment(Environment environment) {  
  50.         this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");  
  51.     }  
  52.       
  53.     @Bean  
  54.     @ConditionalOnMissingBean  
  55.     public SqlSessionFactory sqlSessionFactory() {  
  56.         try {  
  57.             SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();  
  58.             sessionFactory.setDataSource(roundRobinDataSouceProxy());  
  59.             sessionFactory.setTypeAliasesPackage(propertyResolver  
  60.                     .getProperty("typeAliasesPackage"));  
  61.             sessionFactory  
  62.                     .setMapperLocations(new PathMatchingResourcePatternResolver()  
  63.                             .getResources(propertyResolver  
  64.                                     .getProperty("mapperLocations")));  
  65.             sessionFactory  
  66.                     .setConfigLocation(new DefaultResourceLoader()  
  67.                             .getResource(propertyResolver  
  68.                                     .getProperty("configLocation")));  
  69.   
  70.             return sessionFactory.getObject();  
  71.         } catch (Exception e) {  
  72.             logger.warn("Could not confiure mybatis session factory");  
  73.             return null;  
  74.         }  
  75.     }  
  76.       
  77.       
  78.     @Bean  
  79.     public RoundRobinRWRoutingDataSourceProxy roundRobinDataSouceProxy(){  
  80.         RoundRobinRWRoutingDataSourceProxy proxy = new RoundRobinRWRoutingDataSourceProxy();  
  81.         proxy.setWriteDataSource(writeDataSource);  
  82.         proxy.setReadDataSoures(readDataSources);  
  83.         proxy.setReadKey("READ");  
  84.         proxy.setWriteKey("WRITE");  
  85.           
  86.         return proxy;  
  87.     }  
  88.       
  89.     @Bean  
  90.     @ConditionalOnMissingBean  
  91.     public DataSourceTransactionManager transactionManager() {  
  92.         return new DataSourceTransactionManager(writeDataSource);  
  93.     }  
  94. }  

 

 

 

Application.java

 

  1. package com.modou.weixin;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.boot.CommandLineRunner;  
  5. import org.springframework.boot.SpringApplication;  
  6. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;  
  7. import org.springframework.context.annotation.Bean;  
  8. import org.springframework.context.annotation.ComponentScan;  
  9. import org.springframework.context.annotation.Configuration;  
  10.   
  11. import com.modou.weixin.service.HelloWorldService;  
  12.   
  13. /** 
  14.  * Created by chababa on 15/8/22. 
  15.  */  
  16. @Configuration  
  17. @ComponentScan(basePackages={"com.modou.conf","com.modou.weixin"})  
  18. @EnableAutoConfiguration  
  19. public class Application implements CommandLineRunner{  
  20.     @Autowired  
  21.     HelloWorldService helloWorldService;  
  22.       
  23.     public static void main(String[] args) {  
  24.         SpringApplication.run(Application.class, args);  
  25.     }  
  26.   
  27.     @Override  
  28.     public void run(String... args) throws Exception {  
  29.         System.out.println(this.helloWorldService.print());  
  30.     }  
  31.       
  32. }  



 

3、maven pom.xml 相关依赖[我是基于我的多模块依赖,这里只是一个示意],其中配置了jrebel热部署插件,需要搭配jrebel6.2.1,具体配置和下载请转向 http://blog.csdn.net/xiaoyu411502/article/details/48047369

 

    1. <?xml version="1.0"?>  
    2. <project  
    3.     xsi:schemaLocation="http://maven./POM/4.0.0 http://maven./xsd/maven-4.0.0.xsd"  
    4.     xmlns="http://maven./POM/4.0.0" xmlns:xsi="http://www./2001/XMLSchema-instance">  
    5.     <modelVersion>4.0.0</modelVersion>  
    6.     <parent>  
    7.         <groupId>com.modou.weixin</groupId>  
    8.         <artifactId>weixin-boot-parent</artifactId>  
    9.         <version>0.0.1-SNAPSHOT</version>  
    10.         <relativePath>../weixin-boot-parent</relativePath>  
    11.     </parent>  
    12.     <artifactId>weixin-boot-services</artifactId>  
    13.     <name>weixin-boot-services</name>  
    14.     <url>http://maven.</url>  
    15.   
    16.     <properties>  
    17.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
    18.         <springloaded.version>1.2.4.RELEASE</springloaded.version>  
    19.     </properties>  
    20.   
    21.     <dependencies>  
    22.         <dependency>  
    23.             <groupId>com.modou.weixin</groupId>  
    24.             <artifactId>weixin-boot-sdk</artifactId>  
    25.             <version>${project.version}</version>  
    26.         </dependency>  
    27.         <dependency>  
    28.             <groupId>com.modou.weixin</groupId>  
    29.             <artifactId>mybatis-plugin-rw</artifactId>  
    30.             <version>${project.version}</version>  
    31.         </dependency>  
    32.         <dependency>  
    33.             <groupId>org.springframework.boot</groupId>  
    34.             <artifactId>spring-boot-starter-web</artifactId>  
    35.         </dependency>  
    36.         <dependency>  
    37.             <groupId>org.springframework.boot</groupId>  
    38.             <artifactId>spring-boot-starter-actuator</artifactId>  
    39.         </dependency>  
    40.         <dependency>  
    41.             <groupId>org.springframework.boot</groupId>  
    42.             <artifactId>spring-boot-starter-thymeleaf</artifactId>  
    43.         </dependency>  
    44.         <dependency>  
    45.             <groupId>org.springframework</groupId>  
    46.             <artifactId>spring-jdbc</artifactId>  
    47.         </dependency>  
    48.         <dependency>  
    49.             <groupId>javax.persistence</groupId>  
    50.             <artifactId>persistence-api</artifactId>  
    51.         </dependency>  
    52.         <dependency>  
    53.             <groupId>org.mybatis</groupId>  
    54.             <artifactId>mybatis</artifactId>  
    55.         </dependency>  
    56.         <dependency>  
    57.             <groupId>org.mybatis</groupId>  
    58.             <artifactId>mybatis-spring</artifactId>  
    59.         </dependency>  
    60.         <dependency>  
    61.             <groupId>com.alibaba</groupId>  
    62.             <artifactId>druid</artifactId>  
    63.         </dependency>  
    64.         <dependency>  
    65.             <groupId>mysql</groupId>  
    66.             <artifactId>mysql-connector-java</artifactId>  
    67.         </dependency>  
    68.         <dependency>  
    69.             <groupId>com.github.pagehelper</groupId>  
    70.             <artifactId>pagehelper</artifactId>  
    71.         </dependency>  
    72.         <dependency>  
    73.             <groupId>tk.mybatis</groupId>  
    74.             <artifactId>mapper</artifactId>  
    75.         </dependency>  
    76.         <dependency>  
    77.             <groupId>org.mybatis.generator</groupId>  
    78.             <artifactId>mybatis-generator-core</artifactId>  
    79.         </dependency>  
    80.     </dependencies>  
    81.   
    82. </project>  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多