springboot整合多数据源不用JPA springboot 中整合mybatis多数据源不使用JPA
青蛙与大鹅 人气:0前言:
小伙伴说能不能用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,参考:
数据源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进行操作了。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容