欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring boot怎么整合Mybatis

程序员文章站 2023-12-10 10:03:04
 最近刚接触spring boot,正是因为他的及简配置方便开发,促使我下定决心要用它把之前写的项目重构,那么问题来了,spring boot怎么整合mybati...

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

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

【后续更新】

1、文件结构

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

mybatisconfiguration.java也就是mybatis配置核心入口,构建连接创建sqlsessionfactory

Spring boot怎么整合Mybatis

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,具体配置和下载请转向

<?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的方法,希望对大家有所帮助