mybatis调用 import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.Map;import javax.sql.DataSource;import org.apache.commons.io.IOUtils;import org.apache.ibatis.datasource.pooled.PooledDataSource;i
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.apache.commons.io.IOUtils; import org.apache.ibatis.datasource.pooled.PooledDataSource; import org.apache.ibatis.io.Resources; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public final class DataSourceSqlSessionFactory { public static final String CONFIGURATION_PATH = "configuration.xml"; public static final String CONFIGURATION_DB_PATH = "db.properties"; private static final MapSQLSESSIONFACTORYS = new HashMap (); public static SqlSessionFactory getH2SessionFactory(){ return getSqlSessionFactory(DataSourceEnvironment.LOCAL); } public static SqlSessionFactory getEnvSessionFactory(){ return getSqlSessionFactory(DataSourceEnvironment.ENV); } /** * 根据指定的DataSourceEnvironment获取对应的SqlSessionFactory * @param environment 数据源environment * @return SqlSessionFactory */ public static SqlSessionFactory getSqlSessionFactory(DataSourceEnvironment environment) { SqlSessionFactory sqlSessionFactory = SQLSESSIONFACTORYS.get(environment); if (sqlSessionFactory!=null) return sqlSessionFactory; else { InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(CONFIGURATION_PATH); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, environment.name()); } catch (IOException e) { } finally { IOUtils.closeQuietly(inputStream); } SQLSESSIONFACTORYS.put(environment, sqlSessionFactory); return sqlSessionFactory; } } public static void rebuildEnvFactory(String driver, String url,String username,String password){ Configuration config=DataSourceSqlSessionFactory.getConfiguration(); DataSource source=new PooledDataSource( driver, url, username, password); Environment env=new Environment(DataSourceBean.DEFAULT_ENV_NAME,config.getEnvironment().getTransactionFactory(),source); config.setEnvironment(env); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config); SQLSESSIONFACTORYS.put(DataSourceEnvironment.ENV, sqlSessionFactory); } public static Configuration getConfiguration(){ return getEnvSessionFactory().getConfiguration(); } /** * 配置到Configuration.xml文件中的数据源的environment的枚举描述 */ public static enum DataSourceEnvironment { ENV("development"), LOCAL("h2"); private String name; //构造器默认也只能是private, 从而保证构造函数只能在内部使用 DataSourceEnvironment(String name) { this.name = name; } public String getName() { return name; } } }