MyBatis多数据源配置以及Mybatis Generator自动生成代码

在业务中会遇到同一个项目需要使用多个数据源来读取数据,这种情况下就要更改Mybatis的相关配置,本篇将介绍如何去引入多数据源,同时其中会遇到的一些坑也会指出。同时也会说一下如何使用Mybatis Generator。
  1. 找到配置文件,配置第二个数据源配置
    system_config_dev.properties
    文件可能不同 不过大同小异
##############  dataSource0 start  ###############
db0.driverClass=oracle.jdbc.driver.OracleDriver
db0.jdbcUrl=jdbc:oracle:thin:@
db0.username=
db0.password=
db0.initialPoolSize=2
db0.minPoolSize=10
db0.maxPoolSize=20
db0.acquireIncrement=3
db0.maxIdleTime=0
db0.maxStatements=0
db0.acquireRetryAttempts=2
db0.acquireRetryDelay=60
db0.preferredTestQuery=select * from dual
db0.testConnectionOnCheckin=true
db0.idleConnectionTestPeriod=60
##############  dataSource0 end  ###############

##############  dataSource1 start  ###############
db1.driverClass=oracle.jdbc.driver.OracleDriver
db1.jdbcUrl=jdbc:oracle:thin:@
db1.username=
db1.password=
db1.initialPoolSize=20
db1.minPoolSize=20
db1.maxPoolSize=100
db1.acquireIncrement=1
db1.maxIdleTime=0
db1.maxStatements=0
db1.acquireRetryAttempts=2
db1.acquireRetryDelay=60
db1.preferredTestQuery=select * from dual
db1.testConnectionOnCheckin=true
db1.idleConnectionTestPeriod=60
##############  dataSource1 end  ###############
  1. 修改Mybatis的数据源配置bean
    以下情况是在Spring整合Mybatis的配置文件的情况下的配置
    修改applicationContext.xml
<!-- 数据源1 配置 begin -->
    <bean id="ds1" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${db1.driverClass}"/>
        <property name="jdbcUrl" value="${db1.jdbcUrl}"/>
        <property name="user" value="${db1.username}"/>
        <property name="password" value="${db1.password}"/>
        <!--连接池初始化连接数。-->
        <property name="initialPoolSize" value="${db1.initialPoolSize}"/>
        
        <!--连接池中保留的最小连接数。-->  
        <property name="minPoolSize" value="${db1.minPoolSize}"/>
        
        <!--连接池中保留的最大连接数。Default: 15 -->
        <property name="maxPoolSize" value="${db1.maxPoolSize}"/>
        
        <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
        <property name="maxIdleTime" value="${db1.maxIdleTime}"/>
        
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
        <property name="acquireIncrement" value="${db1.acquireIncrement}"/>
        
        <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
        <property name="acquireRetryAttempts" value="${db1.acquireRetryAttempts}"></property>
        
        <!--两次连接中间隔时间,单位毫秒。Default: 1000 -->
        <property name="acquireRetryDelay" value="${db1.acquireRetryDelay}"></property>
        
        <!--定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个一显著提高测试速度。注意:
			测试的表必须在初始数据源的时候就存在。Default: null-->
        <property name="preferredTestQuery" value="${db1.preferredTestQuery}"></property>
        
        <!--如果设为true那么在取得连接的同时将校验连接的有效性。Default: false -->
        <property name="testConnectionOnCheckin" value="${db1.testConnectionOnCheckin}"></property>
        
        <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
        <property name="idleConnectionTestPeriod" value="${db1.idleConnectionTestPeriod}"></property>
        
        <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
			属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
			如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
		<property name="maxStatements" value="${db1.maxStatements}"/>
        <!-- <property name="maxStatements" value="0"/> -->
        
        <!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出 
  			SQLException,如设为0则无限期等待。单位毫秒。Default: 0 --> 
		<property name="checkoutTimeout" value="18000"></property>
		
		<!--配置连接的生存时间,超过这个时间的连接将由连接池自动断开丢弃掉。当然正在使用的连接不会马上断开,而是等待 
			它close再断开。配置为0的时候则不会对连接的生存时间进行限制。Default: 0  -->
		<!-- <property name="maxConnectionAge" value="180"></property> -->
		
		<!--为0的时候要求所有的Connection在应用程序中必须关闭。如果不为0,则强制在设定的时间到达后回收 Connection。Default: 0  -->
		<!-- <property name="unreturnedConnectionTimeout" value="300"></property> -->
		
		<!-- 如果达到最大存活时间后,连接还是不能被连接缓冲池正常关闭,那么肯定出现了连接泄漏,此时,再过30秒后,由连接缓冲池主动执行kill -->
		<!-- <property name="debugUnreturnedConnectionStackTraces" value="true"></property> -->
    </bean>

    <!-- 事务管理器 -->
	<bean id="tm1" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="ds1" />
	</bean>
	
	<!-- 使用annotation注解方式配置事务 -->
	<tx:annotation-driven transaction-manager="tm1"/>

    <!-- 配置mybitasSqlSessionFactoryBean -->
    <bean id="sf1" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="ds1"/>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
    </bean>
    
    <!-- 配置SqlSessionTemplate -->
    <bean id="st1" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sf1"/>
    </bean>
    
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="sqlSessionTemplateBeanName" value="st1"/>
		<property name="basePackage" value="com.你的dao的包路径.dao1" />
	</bean>
<!-- 数据源1 配置 end -->

配置的时候要注意涉及到bean id 和 value的地方, 需要将其修改为对应的数据源编号。


以上即配置完成,同时对于新的数据源可能需要生成对应的数据库操作方法。

  1. 在eclipse→Help→Eclipse Marketplace 中搜索 Mybatis Generator
    点击Eclipse Marketplace
    点击安装
  2. 安装完成后重启Eclipse
  3. 右键项目→New→other→MyBatis Generator Configuration File
    直接下一步生成xml文件
  4. 在项目根目录下找到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>
 
	<!-- targetRuntime:此属性用于指定生成的代码的运行时环境, MyBatis3是默认值 -->
	<!-- id="context1"此处的id用context1也是默认值 -->
	<context id="context1" targetRuntime="MyBatis3">
	
		<commentGenerator>
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="false" />
		</commentGenerator>
 
		<!-- connectionURL:数据库的地址;driverClass:驱动类 -->
		<jdbcConnection connectionURL="jdbc:oracle:thin:@"
			driverClass="oracle.jdbc.driver.OracleDriver" password="" userId="" />
 
		<!-- targetPackage是目标包名, targetProject是包所在的位置 -->
		<javaModelGenerator targetPackage="com.XXXXX.dao1.model"
			targetProject="XXXXX/src" />
 
		<!-- targetPackage放置生成的SQL映射文件, targetProject指定生成SQL映射的目标项目 -->
		<sqlMapGenerator targetPackage="com.XXXXX.dao1.mapper"
			targetProject="XXXXX/src" />
 
		<!-- targetPackage是目标包名, targetProject是包所在的位置;type:XMLMAPPER生成的对象是 MyBatis3.x 
			映射器基础结构的 Java接口 -->
		<javaClientGenerator targetPackage="com.XXXXX.dao1.mapper"
			targetProject="XXXXX/src" type="XMLMAPPER" />
 
		<!-- 数据库里的表名 -->
		<table tableName="ORDER_INFO"></table>
		<table tableName="PASSENGER_INFO"></table>
		<table tableName="SUB_ORDER_INFO"></table>
		<table tableName="SEGMENT_INFO"></table>
 
	</context>
</generatorConfiguration>
  1. 保存后右键→Run As→Run Mybatis Generator
  2. 大功告成,就可以测试是否能对数据库进行增删改查了!

需要注意,在Mybatis中,两个数据源如果拥有同名表,在全部mapper都是自动生成的情况下,mapper的初始化会失败,所以请保证所有mapper不同名,同时记得修改对应mapper映射的xml内的实体类名。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值