Spring boot使用Mybatis

来源:https://www.cnblogs.com/softidea/p/5699969.html

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

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

【后续更新】

1、文件结构

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

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

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

application.yml 相关配置[html]view plaincopy

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

DataBaseConfiguration.java[java]view plaincopy

  1. package com.modou.conf.mybatis;  
  2. import java.util.ArrayList;  
  3. import java.util.List;  
  4. import javax.sql.DataSource;  
  5. import org.slf4j.Logger;  
  6. import org.slf4j.LoggerFactory;  
  7. import org.springframework.boot.bind.RelaxedPropertyResolver;  
  8. import org.springframework.context.EnvironmentAware;  
  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.env.Environment;  
  13. import org.springframework.transaction.annotation.EnableTransactionManagement;  
  14. import com.alibaba.druid.pool.DruidDataSource;  
  15. @Configuration  
  16. @EnableTransactionManagement  
  17. public class DataBaseConfiguration implements EnvironmentAware {  
  18.     private RelaxedPropertyResolver propertyResolver;  
  19.     private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class);  
  20.     @Override  
  21.     public void setEnvironment(Environment env) {  
  22.         this.propertyResolver = new RelaxedPropertyResolver(env, “jdbc.”);  
  23.     }  
  24.     @Bean(name=”writeDataSource”, destroyMethod = “close”, initMethod=”init”)  
  25.     @Primary  
  26.     public DataSource writeDataSource() {  
  27.         log.debug(“Configruing Write DataSource”);  
  28.         DruidDataSource datasource = new DruidDataSource();  
  29.         datasource.setUrl(propertyResolver.getProperty(“url”));  
  30.         datasource.setDriverClassName(propertyResolver.getProperty(“driverClassName”));  
  31.         datasource.setUsername(propertyResolver.getProperty(“username”));  
  32.         datasource.setPassword(propertyResolver.getProperty(“password”));  
  33.         return datasource;  
  34.     }  
  35.     @Bean(name=”readOneDataSource”, destroyMethod = “close”, initMethod=”init”)  
  36.     public DataSource readOneDataSource() {  
  37.         log.debug(“Configruing Read One DataSource”);  
  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.         return datasource;  
  44.     }  
  45.     @Bean(name=”readTowDataSource”, destroyMethod = “close”, initMethod=”init”)  
  46.     public DataSource readTowDataSource() {  
  47.         log.debug(“Configruing Read Two DataSource”);  
  48.         DruidDataSource datasource = new DruidDataSource();  
  49.         datasource.setUrl(propertyResolver.getProperty(“url”));  
  50.         datasource.setDriverClassName(propertyResolver.getProperty(“driverClassName”));  
  51.         datasource.setUsername(propertyResolver.getProperty(“username”));  
  52.         datasource.setPassword(propertyResolver.getProperty(“password”));  
  53.         return datasource;  
  54.     }  
  55.     @Bean(name=”readDataSources”)  
  56.     public List<DataSource> readDataSources(){  
  57.         List<DataSource> dataSources = new ArrayList<DataSource>();  
  58.         dataSources.add(readOneDataSource());  
  59.         dataSources.add(readTowDataSource());  
  60.         return dataSources;  
  61.     }  
  62. }  

MyBatisConfiguration.java[java]view plaincopy

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

Application.java[java]view plaincopy

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

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

  1. <?xml version=”1.0″?>  
  2. <project  
  3.     xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”  
  4.     xmlns=”http://maven.apache.org/POM/4.0.0″ xmlns:xsi=”http://www.w3.org/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.apache.org</url>  
  15.     <properties>  
  16.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  17.         <springloaded.version>1.2.4.RELEASE</springloaded.version>  
  18.     </properties>  
  19.     <dependencies>  
  20.         <dependency>  
  21.             <groupId>com.modou.weixin</groupId>  
  22.             <artifactId>weixin-boot-sdk</artifactId>  
  23.             <version>${project.version}</version>  
  24.         </dependency>  
  25.         <dependency>  
  26.             <groupId>com.modou.weixin</groupId>  
  27.             <artifactId>mybatis-plugin-rw</artifactId>  
  28.             <version>${project.version}</version>  
  29.         </dependency>  
  30.         <dependency>  
  31.             <groupId>org.springframework.boot</groupId>  
  32.             <artifactId>spring-boot-starter-web</artifactId>  
  33.         </dependency>  
  34.         <dependency>  
  35.             <groupId>org.springframework.boot</groupId>  
  36.             <artifactId>spring-boot-starter-actuator</artifactId>  
  37.         </dependency>  
  38.         <dependency>  
  39.             <groupId>org.springframework.boot</groupId>  
  40.             <artifactId>spring-boot-starter-thymeleaf</artifactId>  
  41.         </dependency>  
  42.         <dependency>  
  43.             <groupId>org.springframework</groupId>  
  44.             <artifactId>spring-jdbc</artifactId>  
  45.         </dependency>  
  46.         <dependency>  
  47.             <groupId>javax.persistence</groupId>  
  48.             <artifactId>persistence-api</artifactId>  
  49.         </dependency>  
  50.         <dependency>  
  51.             <groupId>org.mybatis</groupId>  
  52.             <artifactId>mybatis</artifactId>  
  53.         </dependency>  
  54.         <dependency>  
  55.             <groupId>org.mybatis</groupId>  
  56.             <artifactId>mybatis-spring</artifactId>  
  57.         </dependency>  
  58.         <dependency>  
  59.             <groupId>com.alibaba</groupId>  
  60.             <artifactId>druid</artifactId>  
  61.         </dependency>  
  62.         <dependency>  
  63.             <groupId>mysql</groupId>  
  64.             <artifactId>mysql-connector-java</artifactId>  
  65.         </dependency>  
  66.         <dependency>  
  67.             <groupId>com.github.pagehelper</groupId>  
  68.             <artifactId>pagehelper</artifactId>  
  69.         </dependency>  
  70.         <dependency>  
  71.             <groupId>tk.mybatis</groupId>  
  72.             <artifactId>mapper</artifactId>  
  73.         </dependency>  
  74.         <dependency>  
  75.             <groupId>org.mybatis.generator</groupId>  
  76.             <artifactId>mybatis-generator-core</artifactId>  
  77.         </dependency>  
  78.     </dependencies>  
  79. </project>  
http://blog.csdn.net/xiaoyu411502/article/details/48164311
滚动到顶部

免费制作创意短视频活动

复工复产之际,博视优学隆重推出免费制作视频活动——只需告诉我们您的视频需求,我们将免费为您制作一个创意短视频,用于您的营销推广或教学实践等。零成本试水短视频,开放名额有限,机不可失,不要犹豫!