Mybatis整合Druid和H2嵌入式數據庫

Mybatis整合Druid和H2嵌入式數據庫 java

Mybatis的DataSource和Druid的DataSource不兼容,因此須要一個代理 sql

package h2test;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.DataSourceFactory;

public class DruidDataSourceFactory implements DataSourceFactory {
	private DataSource dataSource;

	@Override
	public DataSource getDataSource() {
		return this.dataSource;
	}

	@Override
	public void setProperties(final Properties props) {
		try {
			this.dataSource = com.alibaba.druid.pool.DruidDataSourceFactory.createDataSource(props);
		} catch (final RuntimeException e) {
			throw e;
		} catch (final Exception e) {
			throw new RuntimeException("init datasource error", e);
		}
	}
}

Mybatis配置文件Configuration.xml 數據庫

<?xml version="1.0" encoding="UTF-8" ?> 
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
		"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="lazyLoadingEnabled" value="true"/>
		<setting name="aggressiveLazyLoading" value="false"/>
	</settings>
	<typeAliases>
		<typeAlias type="h2test.DruidDataSourceFactory"	alias="DRUID" />
	</typeAliases>
	<environments default="h2">
		<environment id="derby">
			<transactionManager type="JDBC" />
			<dataSource type="DRUID">
				<property name="url" value="jdbc:derby:data/helloDB" />
				<!-- <property name="initialSize" value="2"/> -->
				<!-- <property name="minIdle" value="4"/> -->
				<property name="removeAbandoned" value="true" />
				<property name="poolPreparedStatements" value="true" />
				<property name="validationQuery" value="values 1" />
				<property name="filters" value="stat"/>
			</dataSource>
		</environment>
		<environment id="h2">
			<transactionManager type="JDBC"/>
			<dataSource type="DRUID">
				<property name="driverClassName" value="org.h2.Driver" />
				<property name="url" value="jdbc:h2:file:db/helloDB;IFEXISTS=TRUE;CIPHER=XTEA;FILE_LOCK=SOCKET" />
				<property name="username" value="admin" />
				<property name="password" value="admin" />
				<!-- <property name="initialSize" value="2"/> -->
				<!-- <property name="minIdle" value="4"/> -->
				<property name="removeAbandoned" value="true" />
				<property name="poolPreparedStatements" value="true" />
				<property name="validationQuery" value="select 1" />
				<property name="filters" value="stat"/>
			</dataSource>
		</environment>
	</environments>
</configuration>
相關文章
相關標籤/搜索