Spring boot Mybatis
最近刚接触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>

http://blog.csdn.net/xiaoyu411502/article/details/48164311/
Spring boot Mybatis的更多相关文章
- spring boot + mybatis + druid
因为在用到spring boot + mybatis的项目时候,经常发生访问接口卡,服务器项目用了几天就很卡的甚至不能访问的情况,而我们的项目和数据库都是好了,考虑到可能时数据库连接的问题,所以我打算 ...
- Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版
一.前言 什么是MyBatis?MyBatis是目前Java平台最为流行的ORM框架https://baike.baidu.com/item/MyBatis/2824918 本篇开发环境1.操作系统: ...
- spring boot + mybatis + druid配置实践
最近开始搭建spring boot工程,将自身实践分享出来,本文将讲述spring boot + mybatis + druid的配置方案. pom.xml需要引入mybatis 启动依赖: < ...
- spring boot+mybatis+quartz项目的搭建完整版
1. 利用spring boot提供的工具(http://start.spring.io/)自动生成一个标准的spring boot项目架构 2. 因为这里我们是搭建spring boot+mybat ...
- 快速搭建一个Spring Boot + MyBatis的开发框架
前言:Spring Boot的自动化配置确实非常强大,为了方便大家把项目迁移到Spring Boot,特意总结了一下如何快速搭建一个Spring Boot + MyBatis的简易文档,下面是简单的步 ...
- spring boot mybatis 打成可执行jar包后启动UnsatisfiedDependencyException异常
我的spring boot + mybatis项目在idea里面执行正常,但发布测试环境打成可执行jar包后就启动失败,提示错误如下: [ ERROR] [2018-08-30 17:23:48] o ...
- Spring Boot + Mybatis + Redis二级缓存开发指南
Spring Boot + Mybatis + Redis二级缓存开发指南 背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybat ...
- Spring Boot + Mybatis 实现动态数据源
动态数据源 在很多具体应用场景的时候,我们需要用到动态数据源的情况,比如多租户的场景,系统登录时需要根据用户信息切换到用户对应的数据库.又比如业务A要访问A数据库,业务B要访问B数据库等,都可以使用动 ...
- Spring boot Mybatis 整合(完整版)
个人开源项目 springboot+mybatis+thymeleaf+docker构建的个人站点开源项目(集成了个人主页.个人作品.个人博客) 朋友自制的springboot接口文档组件swagge ...
- 【转】spring boot mybatis 读取配置文件
spring boot mybatis 配置整理 一.加载mybatis的配置 1.手写配置,写死在代码里 import java.io.IOException; import java.util.P ...
随机推荐
- 【2014】【辛星】【php】【秋季】【2】第一个php程序
<span style="font-family:KaiTi_GB2312;font-size:18px;">*******************设置server** ...
- spring servlet 扩展undertow
官方地址:http://undertow.io/documentation/servlet/servlet-extensions.html 留待学习中,mark一下 源码地址:https://git ...
- Java基础知识强化之集合框架笔记23:ArrayList的实现原理
1. ArrayList的实现原理: 这个可以直接参考网友的博客:http://www.cnblogs.com/ITtangtang/p/3948555.html
- display:table- cell属性的练习
display:table- cell属性指让标签元素以表格单元格的形式呈现,类似于td标签.目前IE8+以及其他现代浏览器都是支持此属性的,但是IE6/7只能对你说 sorry了,这一事实也是大大制 ...
- Activity Threa创建Window和View分析
http://blog.csdn.net/ljsbuct/article/details/7094580 1. 入口. 以前一直都说Activity的人口是onCreate方法.其实android上一 ...
- opencart 模块开发详解
opencart 模块开发详解 由 xiekanxiyang » 2013年 7月 11日 10:17 pm opencart 将页面分成若干模块, 每个模块可以有多个实例(可能这样说不是很恰当) 每 ...
- awk中split函数的用法
time='12:34:56' echo $time | awk '{split($0,a,":" ); print a[1]}' 12 echo $time | awk '{sp ...
- Python:运算符
#!/usr/bin/python3 #运算符 #算术运算符 print("算术运算符:","+ - * / % **(幂) //(取整)") #比较运算符 p ...
- 利用CMake自己创建OpenCV静态链接库
1.准备工作: 1)完成Visual Studio2012安装: 2)下载并解压CMake3.5.0: 3)下载并解压OpenCV2.4.12: 4)下载并解压TBB44_20160128oss. 2 ...
- 如何让低版本的IE浏览器(IE6/IE7/IE8)支持HTML5 header等新标签
html5提供的一些新标签(article,aside,dialog,footer,header,section,footer,nav,figure,menu)使用起来非常的方便,但是低版本的IE浏览 ...