代替mybatis-config.xml,该方法返回SqlSessionFactory,我们就可以获取SqlSession了 SqlSessionFactory mybatisConfig(String driver, String url, String username,String password) throws SQLException {// 获取DataSource,DataSour
SqlSessionFactory mybatisConfig(String driver, String url, String username,
String password) throws SQLException {
// 获取DataSource,DataSource接口有多个实现类,我们用的是mybatis给我们提供的PooledDataSource
PooledDataSource pooledDataSource = new PooledDataSource(driver, url,
username, password);
// 若需要配置pooledDatasource,则可以用他的set方法,如
pooledDataSource.setLoginTimeout(6000);
DataSource dataSource = pooledDataSource;
// 配置事务管理,这里我们使用JDBC的事务
TransactionFactory trcFactory = new JdbcTransactionFactory();
// 配置Environment对象,"development"是我们给起的名字
Environment env = new Environment("development", trcFactory, dataSource);
// 创建Configuration对象
Configuration config = new Configuration(env);
//
中的内容在此处配置
config.setLazyLoadingEnabled(true);
// 起别名
TypeAliasRegistry aliases = config.getTypeAliasRegistry();
aliases.registerAlias("bean", TestBean.class);
// 映射接口,若有xml文件,则xml的文件应和接口文件同名
config.addMapper(DaoMapper.class);
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(config);
return sqlSessionFactory;
}
解析1:配置DataSource
PooledDataSource pooledDataSource = new PooledDataSource(driver, url,username, password); 对应解析2:配置JDBC事务
TransactionFactory trcFactory = new JdbcTransactionFactory(); 对应解析3:配置Environment
Environment env = new Environment("development", trcFactory, dataSource);
对应
解析4:装入Configuration
Configuration config = new Configuration(env); 对应解析5:配置别名------- config.setLazyLoadingEnabled(true); 对应
TypeAliasRegistry aliases = config.getTypeAliasRegistry();
aliases.registerAlias("bean", TestBean.class);
对应
解析6:添加映射XML,xml名称应和DaoMapper.class并且在同一个包下
config.addMapper(DaoMapper.class); 对应xml和java文件应同名且在同一个包下 对应的mybatisConfig.xml
