Spring boot Mybatis

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

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

【后续更新】

 

1、文件结构

 

 

 

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

 

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

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

application.yml 相关配置

 

[html] view plain copy

 

  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

 

[java] view plain copy

 

  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

 

[java] view plain copy

 

  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

 

[java] view plain copy

 

  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

 

[html] view plain copy

 

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

http://blog.csdn.net/xiaoyu411502/article/details/48164311

 

时间: 2024-10-28 04:31:25

Spring boot Mybatis的相关文章

spring boot+mybatis的整合

问题描述 spring boot+mybatis的整合 在官网找了很久没看到有关于spring boot跟mybatis的整合,求高手指点 解决方案 完整参考:http://blog.csdn.net/xiaoyu411502/article/details/48164311 解决方案二: 官方版本没有提供支持,好像只能使用原始的方法整合了

Spring Boot MyBatis 通用Mapper插件集成

看本文之前,请确保你已经在SpringBoot中集成MyBatis,并能正常使用. 如果没有,那么请先移步 http://blog.csdn.net/catoop/article/details/50553714 做了解后,再按本文步骤操作. 使用MyBatis在我们通过xml集中配置SQL,并通过创建接口Mapper文件来完成持久化DAO层(mybatis内部使用的是动态代理,所以我们不需要自己编写实现类). 然而在实际开发中,单表操作非常多,如果你也想像JPA.JDBC那样做一个所谓的Bas

Spring Boot MyBatis 通用Mapper插件集成 good

看本文之前,请确保你已经在SpringBoot中集成MyBatis,并能正常使用.如果没有,那么请先移步 http://blog.csdn.net/catoop/article/details/50553714 做了解后,再按本文步骤操作. 使用MyBatis在我们通过xml集中配置SQL,并通过创建接口Mapper文件来完成持久化DAO层(mybatis内部使用的是动态代理,所以我们不需要自己编写实现类). 然而在实际开发中,单表操作非常多,如果你也想像JPA.JDBC那样做一个所谓的Base

Spring Boot MyBatis 连接数据库

最近比较忙,没来得及抽时间把MyBatis的集成发出来,其实mybatis官网在2015年11月底就已经发布了对SpringBoot集成的Release版本,Github上有代码:https://github.com/mybatis/mybatis-spring-boot 前面对JPA和JDBC连接数据库做了说明,本文也是参考官方的代码做个总结. 先说个题外话,SpringBoot默认使用 org.apache.tomcat.jdbc.pool.DataSource 现在有个叫 HikariCP

Spring Boot 整合 Mybatis Annotation 注解的完整 Web 案例

摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 公司需要人.产品.业务和方向,方向又要人.产品.业务和方向,方向- 循环』 本文提纲 一.前言 二.运行 springboot-mybatis-annotation 工程 三.springboot-mybatis-annotation 工程配置详解 四.小结 运行环境:JDK 7 或 8.Maven 3.0+技术栈:SpringBoot 1.5+.SpringBoot Mybatis

Spring Boot 整合 Mybatis 实现 Druid 多数据源详解

本文提纲一.多数据源的应用场景二.运行 springboot-mybatis-mutil-datasource 工程案例三.springboot-mybatis-mutil-datasource 工程代码配置详解 一.多数据源的应用场景 目前,业界流行的数据操作框架是 Mybatis,那 Druid 是什么呢? Druid 是 Java 的数据库连接池组件.Druid 能够提供强大的监控和扩展功能.比如可以监控 SQL ,在监控业务可以查询慢查询 SQL 列表等.Druid 核心主要包括三部分:

Spring Data JPA方法定义规范【从零开始学Spring Boot】

视频&交流平台] à SpringBoot网易云课堂视频 http://study.163.com/course/introduction.htm?courseId=1004329008 à Spring Boot交流平台 http://412887952-qq-com.iteye.com/blog/2321532           事情的起因:有人问过我们这个这个问题:为什么我利用Spring data jpa写的方法没有按照我想要的情况进行执行呢?我记得当时只是告诉他你你先看看Spring

57. Spring 自定义properties升级篇【从零开始学Spring Boot】

 注解ConfigurationProperties和EnableAutoConfiguration的区别: @EnableConfigurationProperties tells Spring to treat this class as a consumer of application.yml/properties values( {@link ConfigurationProperties} beans can be registered in the standard way (fo

Spring Boot 集成 FreeMarker 详解案例

转载自 并发编程网 - ifeve.com一.Springboot 那些事 SpringBoot 很方便的集成 FreeMarker ,DAO 数据库操作层依旧用的是 Mybatis,本文将会一步一步到来如何集成 FreeMarker 以及配置的详解: Springboot 那些事: 系类文章: <Spring Boot 之 RESRful API 权限控制> <Spring Boot 之 HelloWorld详解> <Springboot 整合 Mybatis 的完整 We