Spring boot怎么整合Mybatis

 更新时间:2017年07月11日 11:02:45   作者:茶爸爸  
spring boot的简配置方便的开发,下面通过本文给大家分享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> 

以上所述是小编给大家介绍的Spring boot整合Mybatis的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • SpringCloud服务的平滑上下线的方法

    SpringCloud服务的平滑上下线的方法

    这篇文章主要介绍了SpringCloud服务的平滑上下线的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-06-06
  • Struts2实现生成动态验证码并验证实例代码

    Struts2实现生成动态验证码并验证实例代码

    这篇文章主要介绍了Struts2实现生成动态验证码并验证实例代码的相关资料,非常不错具有参考借鉴价值,需要的朋友可以参考下
    2016-06-06
  • Effective Java (异常处理)

    Effective Java (异常处理)

    Effective Java (异常处理),需要的朋友可以参考一下
    2013-02-02
  • MyBatis一二级缓存

    MyBatis一二级缓存

    这篇文章主要介绍了MyBatis一二级缓存的相关知识,非常不错,具有参考借鉴价值,需要的朋友可以参考下
    2017-06-06
  • IntelliJ IDEA远程Debug Linux的Java程序,找问题不要只会看日志了(推荐)

    IntelliJ IDEA远程Debug Linux的Java程序,找问题不要只会看日志了(推荐)

    这篇文章主要介绍了IntelliJ IDEA远程Debug Linux的Java程序,找问题不要只会看日志了,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • Java绘图库JFreeChart的使用教程

    Java绘图库JFreeChart的使用教程

    图表是一种以简单方式显示信息的图形,JFreeChart允许创建各种交互式和非交互式图表,本文主要介绍了Java绘图库JFreeChart的使用教程,感兴趣的可以了解一下
    2023-09-09
  • Springboot RocketMq实现过程详解

    Springboot RocketMq实现过程详解

    这篇文章主要介绍了Springboot RocketMq实现过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05
  • Spring事务失效场景的详细整理

    Spring事务失效场景的详细整理

    Spring 事务的传播特性说的是,当多个事务同时存在的时候,Spring 如何处理这些事务的特性,下面这篇文章主要给大家介绍了关于Spring事务失效场景的相关资料,需要的朋友可以参考下
    2022-02-02
  • springboot使用Mybatis(xml和注解)过程全解析

    springboot使用Mybatis(xml和注解)过程全解析

    这篇文章主要介绍了springboot使用Mybatis(xml和注解)过程全解析 ,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-05-05
  • SpringBoot整合阿里云短信服务的案例代码

    SpringBoot整合阿里云短信服务的案例代码

    这篇文章主要介绍了SpringBoot整合阿里云短信服务的案例代码,在Spring Boot项目的pom.xml文件中添加阿里云短信服务SDK的依赖,本文通过示例代码给大家介绍的非常详细,需要的朋友参考下吧
    2024-06-06

最新评论