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

在我的代码当中是实现了数据库读写分离的,所以代码仅做参考,如有需要可以加我微信:benyzhous
【后续更新】
1、文件结构
DataBaseConfiguration.Java用来获取数据库连接配置信息,配置从application.properties中读取
MybatisConfiguration.java也就是MyBatis配置核心入口,构建连接创建SqlSessionFactory
2、下面直接贴代码,有问题的话可以留言或者加我的微信公众号:cha-baba,或者个人微信号:benyzhous
application.yml 相关配置
# Server settings server: port:8080 address:localhost # DATASOURCE jdbc: driverClass: com.mysql.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/local-kaishustory?useUnicode=true&characterEncoding=utf-8 username: root password: root # SPRING PROFILES spring: # HTTP ENCODING http: encoding.charset: UTF-8 encoding.enable: true encoding.force: true # WeiXin Configuration weixin: mp: appid: xx secret: ee token: weixin aeskey: # MyBatis mybatis: typeAliasesPackage: com.modou.**.domain mapperLocations: classpath:/com/modou/**/mapper/*.xml configLocation: classpath:/mybatis-config.xml # LOGGING logging: level: com.ibatis:DEBUG
DataBaseConfiguration.java
package com.modou.conf.mybatis;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {
private RelaxedPropertyResolver propertyResolver;
private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class);
@Override
public void setEnvironment(Environment env) {
this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.");
}
@Bean(name="writeDataSource", destroyMethod = "close", initMethod="init")
@Primary
public DataSource writeDataSource() {
log.debug("Configruing Write DataSource");
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(propertyResolver.getProperty("url"));
datasource.setDriverClassName(propertyResolver.getProperty("driverClassName"));
datasource.setUsername(propertyResolver.getProperty("username"));
datasource.setPassword(propertyResolver.getProperty("password"));
return datasource;
}
@Bean(name="readOneDataSource", destroyMethod = "close", initMethod="init")
public DataSource readOneDataSource() {
log.debug("Configruing Read One DataSource");
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(propertyResolver.getProperty("url"));
datasource.setDriverClassName(propertyResolver.getProperty("driverClassName"));
datasource.setUsername(propertyResolver.getProperty("username"));
datasource.setPassword(propertyResolver.getProperty("password"));
return datasource;
}
@Bean(name="readTowDataSource", destroyMethod = "close", initMethod="init")
public DataSource readTowDataSource() {
log.debug("Configruing Read Two DataSource");
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(propertyResolver.getProperty("url"));
datasource.setDriverClassName(propertyResolver.getProperty("driverClassName"));
datasource.setUsername(propertyResolver.getProperty("username"));
datasource.setPassword(propertyResolver.getProperty("password"));
return datasource;
}
@Bean(name="readDataSources")
public List<DataSource> readDataSources(){
List<DataSource> dataSources = new ArrayList<DataSource>();
dataSources.add(readOneDataSource());
dataSources.add(readTowDataSource());
return dataSources;
}
}
MyBatisConfiguration.java
package com.modou.conf.mybatis;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.plugin.rw.RoundRobinRWRoutingDataSourceProxy;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
*
* 获取第二个数据库的连接信息,在application.yml中配置,并指定特定的前缀
*
*/
@Configuration
@ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class })
@AutoConfigureAfter({ DataBaseConfiguration.class })
@MapperScan(basePackages={"com.modou.**.mapper","com.github.abel533.entity.mapper"})
public class MybatisConfiguration implements EnvironmentAware{
private static Log logger = LogFactory.getLog(MybatisConfiguration.class);
private RelaxedPropertyResolver propertyResolver;
@Resource(name="writeDataSource")
private DataSource writeDataSource;
@Resource(name="readDataSources")
private List<Object> readDataSources;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
}
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory() {
try {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(roundRobinDataSouceProxy());
sessionFactory.setTypeAliasesPackage(propertyResolver
.getProperty("typeAliasesPackage"));
sessionFactory
.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(propertyResolver
.getProperty("mapperLocations")));
sessionFactory
.setConfigLocation(new DefaultResourceLoader()
.getResource(propertyResolver
.getProperty("configLocation")));
return sessionFactory.getObject();
} catch (Exception e) {
logger.warn("Could not confiure mybatis session factory");
return null;
}
}
@Bean
public RoundRobinRWRoutingDataSourceProxy roundRobinDataSouceProxy(){
RoundRobinRWRoutingDataSourceProxy proxy = new RoundRobinRWRoutingDataSourceProxy();
proxy.setWriteDataSource(writeDataSource);
proxy.setReadDataSoures(readDataSources);
proxy.setReadKey("READ");
proxy.setWriteKey("WRITE");
return proxy;
}
@Bean
@ConditionalOnMissingBean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(writeDataSource);
}
}
Application.java
package com.modou.weixin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.modou.weixin.service.HelloWorldService;
/**
* Created by chababa on 15/8/22.
*/
@Configuration
@ComponentScan(basePackages={"com.modou.conf","com.modou.weixin"})
@EnableAutoConfiguration
public class Application implements CommandLineRunner{
@Autowired
HelloWorldService helloWorldService;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println(this.helloWorldService.print());
}
}
3、maven pom.xml 相关依赖[我是基于我的多模块依赖,这里只是一个示意],其中配置了jrebel热部署插件,需要搭配jrebel6.2.1,具体配置和下载请转向 http://blog.csdn.net/xiaoyu411502/article/details/48047369
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.modou.weixin</groupId>
<artifactId>weixin-boot-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../weixin-boot-parent</relativePath>
</parent>
<artifactId>weixin-boot-services</artifactId>
<name>weixin-boot-services</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<springloaded.version>1.2.4.RELEASE</springloaded.version>
</properties>
<dependencies>
<dependency>
<groupId>com.modou.weixin</groupId>
<artifactId>weixin-boot-sdk</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.modou.weixin</groupId>
<artifactId>mybatis-plugin-rw</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
</dependency>
</dependencies>
</project>
以上所述是小编给大家介绍的Spring boot整合Mybatis的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
# spring
# boot
# 整合mybatis
# springboot与mybatis整合实例详解(完美融合)
# Spring Boot整合mybatis(一)实例代码
# Spring Boot+Mybatis的整合过程
# Spring Boot 整合 Mybatis Annotation 注解的完整 Web 案例
# Spring Boot整合MyBatis操作过程
# 详解Spring Boot整合Mybatis实现 Druid多数据源配置
# spring Boot与Mybatis整合优化详解
# 小编
# 我是
# 几个
# 来了
# 在此
# 如有
# 第二个
# 给大家
# 要用
# 使我
# 只是一个
# 所述
# 给我留言
# 下定决心
# 加我
# 正是因为
# 感谢大家
# 它把
# 重构
# 疑问请
相关文章:
网站制作与设计教程,如何制作一个企业网站,建设网站的基本步骤有哪些?
齐河建站公司:营销型网站建设与SEO优化双核驱动策略
表情包在线制作网站免费,表情包怎么弄?
济南专业网站制作公司,济南信息工程学校怎么样?
Python文件管理规范_工程实践说明【指导】
如何快速搭建高效WAP手机网站吸引移动用户?
如何制作公司的网站链接,公司想做一个网站,一般需要花多少钱?
,购物网站怎么盈利呢?
,柠檬视频怎样兑换vip?
建站主机SSH密钥生成步骤及常见问题解答?
,如何利用word制作宣传手册?
陕西网站制作公司有哪些,陕西凌云电器有限公司官网?
邀请函制作网站有哪些,有没有做年会邀请函的网站啊?在线制作,模板很多的那种?
XML的“混合内容”是什么 怎么用DTD或XSD定义
网站制作话术技巧,网站推广做的好怎么话术?
高防服务器租用指南:配置选择与快速部署攻略
建站之星安装需要哪些步骤及注意事项?
如何选择长沙网站建站模板?H5响应式与品牌定制哪个更优?
制作网站公司那家好,网络公司是做什么的?
网站视频怎么制作,哪个网站可以免费收看好莱坞经典大片?
,怎么用自己头像做动态表情包?
开心动漫网站制作软件下载,十分开心动画为何停播?
宝塔建站助手安装配置与建站模板使用全流程解析
制作国外网站的软件,国外有哪些比较优质的网站推荐?
西安大型网站制作公司,西安招聘网站最好的是哪个?
建站之星如何助力网站排名飙升?揭秘高效技巧
建站之星安装失败:服务器环境不兼容?
网站制作知乎推荐,想做自己的网站用什么工具比较好?
如何在沈阳梯子盘古建站优化SEO排名与功能模块?
南阳网站制作公司推荐,小学电子版试卷去哪里找资源好?
如何在Windows虚拟主机上快速搭建网站?
常州自助建站工具推荐:低成本搭建与模板选择技巧
如何在阿里云虚拟机上搭建网站?步骤解析与避坑指南
官网自助建站平台指南:在线制作、快速建站与模板选择全解析
想学网站制作怎么学,建立一个网站要花费多少?
宁波免费建站如何选择可靠模板与平台?
如何解决ASP生成WAP建站中文乱码问题?
c++怎么编写动态链接库dll_c++ __declspec(dllexport)导出与调用【方法】
如何高效完成独享虚拟主机建站?
公司网站设计制作厂家,怎么创建自己的一个网站?
如何在IIS管理器中快速创建并配置网站?
制作企业网站建设方案,怎样建设一个公司网站?
官网自助建站系统:SEO优化+多语言支持,快速搭建专业网站
如何通过远程VPS快速搭建个人网站?
红河网站制作公司,红河事业单位身份证如何上传?
胶州企业网站制作公司,青岛石头网络科技有限公司怎么样?
网站好制作吗知乎,网站开发好学吗?有什么技巧?
如何在云主机上快速搭建网站?
,石家庄四十八中学官网?
如何彻底卸载建站之星软件?
*请认真填写需求信息,我们会在24小时内与您取得联系。