springboot 中整合mybatis多數據源不使用JPA
前言:
小夥伴說能不能用springboot整合一下mybatis多數據源不使用JPA進行數據庫連接操作。那麼說幹就幹
創建一個springboot項目
流程就不介紹瞭,按圖操作即可
創建項目後可能會發現,這個項目展示的有些不對勁啊,java類前面還有個小J號,這是由於maven包還沒有下載成功,你隻需
要去maven projects中重新加載一下就可以瞭。?maven project在哪。。看下圖
項目創建成功瞭,那麼開始說下整合mybatis
首先在我們的resources目錄下存在一個application.properties文件,這是一個全局配置文件,先將兩個數據源配置添加到這個文件中(如果你分環境瞭可以將數據源配置放在不同的目錄下)
//數據源1 spring.datasource.druid.crmtest.driver-class-name=com.mysql.jdbc.Driver spring.datasource.druid.crmtest.url=jdbc:mysql://xxxxx:3306/crm spring.datasource.druid.crmtest.username=xxx spring.datasource.druid.crmtest.password=xxx spring.datasource.druid.crmtest.initial-size=2 spring.datasource.druid.crmtest.max-active=10 spring.datasource.druid.crmtest.min-idle=2 spring.datasource.druid.crmtest.max-wait=30000 spring.datasource.druid.crmtest.validation-query=SELECT 1 spring.datasource.druid.crmtest.validation-query-timeout=30000 spring.datasource.druid.crmtest.min-evictable-idle-time-millis=300000 spring.datasource.druid.crmtest.pool-prepared-statements=true spring.datasource.druid.crmtest.max-pool-prepared-statement-per-connection-size=20 spring.datasource.druid.crmtest.test-on-borrow=false spring.datasource.druid.crmtest.test-on-return=false spring.datasource.druid.crmtest.test-while-idle=true spring.datasource.druid.crmtest.time-between-eviction-runs-millis=60000 spring.datasource.druid.crmtest.filters=stat,wall spring.datasource.druid.crmtest.connection-properties=druid.stat.slowSqlMillis=5000 spring.datasource.druid.crmtest.connection-init-sqls=set names utf8mb4; #數據源2 spring.datasource.druid.paytest.driver-class-name=com.mysql.jdbc.Driver spring.datasource.druid.paytest.url=jdbc:mysql://xxxxxxx:3306/pay spring.datasource.druid.paytest.username=xxxx spring.datasource.druid.paytest.password=xxxxxx spring.datasource.druid.paytest.initial-size=2 spring.datasource.druid.paytest.max-active=10 spring.datasource.druid.paytest.min-idle=2 spring.datasource.druid.paytest.max-wait=30000 spring.datasource.druid.paytest.validation-query=SELECT 1 spring.datasource.druid.paytest.validation-query-timeout=30000 spring.datasource.druid.paytest.min-evictable-idle-time-millis=300000 spring.datasource.druid.paytest.pool-prepared-statements=true spring.datasource.druid.paytest.max-pool-prepared-statement-per-connection-size=20 spring.datasource.druid.paytest.test-on-borrow=false spring.datasource.druid.paytest.test-on-return=false spring.datasource.druid.paytest.test-while-idle=true spring.datasource.druid.paytest.time-between-eviction-runs-millis=60000 spring.datasource.druid.paytest.filters=stat,wall spring.datasource.druid.paytest.connection-properties=druid.stat.slowSqlMillis=5000 spring.datasource.druid.paytest.connection-init-sqls=set names utf8mb4;
創建DataSourceConfig
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.github.pagehelper.PageInterceptor; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.*; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.Properties; /** * @Auther: lqf * @Date: 2018/5/22 * @Description: */ @Configuration @EnableTransactionManagement public class DevDataSourceConfig { //數據源1 在springboot中做多中配置的時候需要 @Primary否則會報錯,springboot需要知道主配置是什麼 @Primary @Bean("crmds") @ConfigurationProperties("spring.datasource.druid.crmtest") public DataSource crmDataSource() { return DruidDataSourceBuilder.create().build(); } //數據源2 @ConfigurationProperties("spring.datasource.druid.paytest")這個配置會自動引入你在配置文件中的配置 @Bean("payds") @ConfigurationProperties("spring.datasource.druid.paytest") public DataSource payDataSource() { return DruidDataSourceBuilder.create().build(); } }
上面是一個總的配置將不同的數據源都配置在瞭這一個configuration中。下面我們來建立單獨的數據源配置(這裡需要註意一點我們看上面引用的是druid,那麼我們需要在pom文件中導入alibaba.druid包,在文章的最後面我會給大傢展示一下pom文件)
數據源1
package com.mysql.test.demo.config; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; /** * @Auther: lqf * @Date: 2018/5/23 * @Description: */ @Configuration @MapperScan(basePackages = {"com.mysql.test.demo.dao.crm"}, sqlSessionTemplateRef = "crmSqlSessionTemplate") public class CrmMysqlConfig implements ApplicationContextAware { private ApplicationContext ctx; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.ctx = applicationContext; } @Bean("crmSqlSessionFactory") public SqlSessionFactoryBean crmSqlSessionFactory(@Qualifier("crmds") DataSource crmDataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(crmDataSource); factoryBean.setTypeAliasesPackage("com.mysql.test.demo.entity.crm"); Resource[] resources = ctx.getResources("classpath*:/mapper/crm/*.xml"); factoryBean.setMapperLocations(resources); return factoryBean; } @Bean("crmSqlSessionTemplate") public SqlSessionTemplate crmSqlSessionTemplate(@Qualifier("crmSqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean("crmTxManager") public DataSourceTransactionManager crmTxManager(@Qualifier("crmds") DataSource crmDataSource) { return new DataSourceTransactionManager(crmDataSource); } }
上面的配置可以直接使用
路徑需要更換成你的項目路徑這裡就不多說瞭,註重提下註解的含義吧。
@Configuration
: 用於定義配置類,可替換xml配置文件,被註解的類內部包含有一個或多個被@Bean註解的方法,這些方法將會被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext類進行掃描,並用於構建bean定義,初始化Spring容器@MapperScan()
: 指定要掃描的Mapper類的包的路徑,sqlSessionTemplateRef :SqlSessionTemplate實現瞭SqlSession,這就是說要對MyBatis的SqlSession進行簡易替換。SqlSessionTemplate通常是被用來替代默認的MyBatis實現的DefaultSqlSession,因為它不能參與到Spring的事務中也不能被註入,因為它是線程不安全的。相同應用程序中兩個類之間的轉換可能會引起數據一致性的問題-
@Qualifier
:我的理解就是告訴指定具體引用那個bean,參考://www.jb51.net/article/220973.htm
數據源2
package com.mysql.test.demo.config; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; /** * @Auther: lqf * @Date: 2018/5/23 * @Description: */ @Configuration @MapperScan(basePackages = {"com.mysql.test.demo.dao.pay"}, sqlSessionTemplateRef = "paySqlSessionTemplate") public class PayMysqlConfig implements ApplicationContextAware { private ApplicationContext ctx; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.ctx = applicationContext; } @Bean("paySqlSessionFactory") public SqlSessionFactoryBean crmSqlSessionFactory(@Qualifier("payds") DataSource payDataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(payDataSource); factoryBean.setTypeAliasesPackage("com.mysql.test.demo.entity.pay"); Resource[] resources = ctx.getResources("classpath*:/mapper/pay/*.xml"); factoryBean.setMapperLocations(resources); return factoryBean; } @Bean("paySqlSessionTemplate") public SqlSessionTemplate crmSqlSessionTemplate(@Qualifier("paySqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean("payTxManager") public DataSourceTransactionManager crmTxManager(@Qualifier("payds") DataSource crmDataSource) { return new DataSourceTransactionManager(crmDataSource); } }
在pom文件中添加generator-maven插件讓我們來測試一下(文章最後展示全部pom文件)
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <configurationFile>./src/main/resources/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <!-- 數據庫驅動 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> </dependencies> </plugin> </plugins> <finalName>agentapi</finalName> </build>
創建generatorConfig.properties文件放在resources目錄下
//數據庫連接路徑 mysql.jdbc.connectionURL=jdbc:mysql://xxxxxx:3306/crm?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull mysql.jdbc.userId=xxx mysql.jdbc.password=xxx //自動生成實體類路徑包名 module.targetPackage=com.mysql.test.demo.entity.crm //生成實體類路徑位置 module.targetProject=src/main/java //生成mapper.xml位置和包名 map.targetPackage=mapper map.targetProject=src/main/resources //生成DAO的包名和位置 client.targetPackage=com.mysql.test.demo.dao.crm client.targetProject=src/main/java
創建generatorConfig.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <properties resource="generatorConfig.properties"/> <context id="bTables" targetRuntime="MyBatis3"> <plugin type="org.mybatis.generator.plugins.RowBoundsPlugin"></plugin> <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin"></plugin> <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin> <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"></plugin> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自動生成的註釋 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--數據庫鏈接URL,用戶名、密碼 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="${mysql.jdbc.connectionURL}" userId="${mysql.jdbc.userId}" password="${mysql.jdbc.password}"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置 --> <javaModelGenerator targetPackage="${module.targetPackage}" targetProject="${module.targetProject}"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置 --> <sqlMapGenerator targetPackage="${map.targetPackage}" targetProject="${map.targetProject}"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="${client.targetPackage}" targetProject="${client.targetProject}"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!--<table tableName="order_history_tab" domainObjectName="OrderHistoryTab" mapperName="OrderHistoryTabMapper">--> <!--<generatedKey column="id" sqlStatement="JDBC"/>--> <!--</table>--> //你要生成的表 <table tableName="fy_advertisement" domainObjectName="FyAdvertisement" mapperName="FyAdvertisementMapper"> <generatedKey column="id" sqlStatement="JDBC"/> </table> </context> </generatorConfiguration>
如果上面的配置都完成的話那麼我們來自動生成一下
如上圖打開maven projects如上圖進行操作就可自動生成需要的mapper 實體 dao等信息。上圖是生成瞭一個數據源的那麼我們來生成第二個數據源中的表操作如上圖,需要改變第二個數據源的位置信息等。(重復的事情就不做瞭和上面生成一樣的道理,隻是改些路徑和對應的表名)
在下圖兩個數據源完全生成好後的目錄結構
項目到這裡就已經整合完成瞭,之後就可以正常的創建service,controller進行操作瞭。
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。
推薦閱讀:
- tk-mybatis整合springBoot使用兩個數據源的方法
- springboot多模塊化整合mybatis,mapper自動註入失敗問題及解決
- 一文詳解Spring加載properties文件的方式
- springboot配置多數據源並集成Druid和mybatis的操作
- 使用Spring掃描Mybatis的mapper接口的三種配置