bonecp是一款开源的、高效的数据库连接池组件,它号称是现在最快的连接池组件,官网上称是dbcp的25倍,但是iBATIS3并没有为它开发类厂,iBATIS3只支持3中类型的类厂,分别是UNPOOLED,POOLED和JNDI,要想集成只能自己开发了,自己开发也不难,只要实现DataSourceFactory接口就可以了,代码很简单:
package com.ibatis.factory;
import com.jolbox.bonecp.BoneCPDataSource;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import javax.sql.DataSource;
import java.util.Properties;
public class BoneCPFactory
implements DataSourceFactory
{
private static final String DRIVER_PROPERTY_PREFIX = "driver.";
private static final int DRIVER_PROPERTY_PREFIX_LENGTH = DRIVER_PROPERTY_PREFIX.length();
private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
private DataSource dataSource;
public BoneCPFactory()
{
// 创建bonecp datasource
dataSource = new BoneCPDataSource();
}
public DataSource getDataSource()
{
return dataSource;
}
/**
* 配置属性
*/
public void setProperties(Properties properties)
{
Properties driverProperties = new Properties();
MetaObject metaDataSource = MetaObject.forObject(dataSource, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY);
for (Object key : properties.keySet())
{
String propertyName = (String) key;
// 处理driver.xxx属性,e.g driver.encoding=UTF8
if (propertyName.startsWith(DRIVER_PROPERTY_PREFIX))
{
String value = properties.getProperty(propertyName);
driverProperties.setProperty(propertyName.substring(DRIVER_PROPERTY_PREFIX_LENGTH), value);
}
else
{
// 利用反射技术,初始化datasource属性的值
if (metaDataSource.hasSetter(propertyName))
{
String value = (String) properties.get(propertyName);
Object convertedValue = convertValue(metaDataSource, propertyName, value);
metaDataSource.setValue(propertyName, convertedValue);
}
}
}
// 如果配置driver.xxx属性,初始化
if (driverProperties.size() > 0)
{
metaDataSource.setValue("driverProperties", driverProperties);
}
}
/**
* 转换数字和Boolean型
*
* @param metaDataSource
* @param propertyName
* @param value
* @return
*/
@SuppressWarnings ("unchecked")
private Object convertValue(MetaObject metaDataSource, String propertyName, String value)
{
Object convertedValue = value;
Class targetType = metaDataSource.getSetterType(propertyName);
if (targetType == Integer.class || targetType == int.class)
{
convertedValue = Integer.valueOf(value);
}
else if (targetType == Long.class || targetType == long.class)
{
convertedValue = Long.valueOf(value);
}
else if (targetType == Boolean.class || targetType == boolean.class)
{
convertedValue = Boolean.valueOf(value);
}
return convertedValue;
}
}
然后在Configuration.xml配置就可以了,首先配置类厂别名:
接着配置environmen:
需要配置的属性很简单,就是BoneCPDataSource类的属性。如此就大功告成了。