您好,登錄后才能下訂單哦!
小編給大家分享一下springboot中如何整合mybatis多數據源不使用JPA,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
流程就不介紹了,按圖操作即可
創建項目后可能會發現,這個項目展示的有些不對勁啊,java類前面還有個小J號,這是由于maven包還沒有下載成功,你只需
要去maven projects中重新加載一下就可以了。?maven project在哪。。看下圖
首先在我們的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.mlszssj.com/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進行操作了。
看完了這篇文章,相信你對“springboot中如何整合mybatis多數據源不使用JPA”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。