下面列出了org.springframework.core.NestedIOException#org.apache.ibatis.mapping.Environment 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public Configuration initMybatisConfiguration(Environment environment, Reader reader, Properties properties) {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
Configuration configuration = parser.getConfiguration();
if(databaseType != null) {
configuration.setDatabaseId(databaseType);
}
configuration.setEnvironment(environment);
initMybatisTypeHandlers(configuration);
initCustomMybatisMappers(configuration);
configuration = parseMybatisConfiguration(configuration, parser);
return configuration;
}
private void environmentsElement(XNode context) throws Exception {
if (context != null) {
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
if (isSpecifiedEnvironment(id)) {
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
DataSource dataSource = dsFactory.getDataSource();
Environment.Builder environmentBuilder = new Environment.Builder(id)
.transactionFactory(txFactory)
.dataSource(dataSource);
configuration.setEnvironment(environmentBuilder.build());
}
}
}
}
/**
* 获取SqlSession
* @return
* @throws IOException
*/
public SqlSession getSqlSession() throws IOException, ClassNotFoundException {
org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
config.setCallSettersOnNulls(true); // 设计null调用setter方法
config.setMapUnderscoreToCamelCase(true); // 驼峰命名支持
// 设置mapper
config.addMappers(targetPackage);
// 设置数据源,事务
PooledDataSourceFactory dataSourceFactory = new PooledDataSourceFactory();
dataSourceFactory.setProperties(DBHelper.properties);
DataSource dataSource = dataSourceFactory.getDataSource();
JdbcTransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("test", transactionFactory, dataSource);
config.setEnvironment(environment);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(config);
return sqlSessionFactory.openSession(true);
}
@SuppressWarnings("all")
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = getConfiguration().getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
DataSource ds = DataSourceHolder.currentDataSource().getNative();
if (ds == null) {
ds = environment.getDataSource();
}
tx = transactionFactory.newTransaction(ds, level, autoCommit);
final Executor executor = getConfiguration().newExecutor(tx, execType);
return new DefaultSqlSession(getConfiguration(), executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
public Configuration initMybatisConfiguration(Environment environment, Reader reader, Properties properties) {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
Configuration configuration = parser.getConfiguration();
if (databaseType != null) {
configuration.setDatabaseId(databaseType);
}
configuration.setEnvironment(environment);
initCustomMybatisMappers(configuration);
initMybatisTypeHandlers(configuration);
initCustomMybatisInterceptors(configuration);
if (isEnableLogSqlExecutionTime()) {
initMyBatisLogSqlExecutionTimePlugin(configuration);
}
configuration = parseMybatisConfiguration(parser);
return configuration;
}
@Override
protected void doStart(final String storeName, final Map<String, String> attributes) throws Exception {
boolean isContentStore = !CONFIG_DATASTORE_NAME.equalsIgnoreCase(storeName);
dataSource = new HikariDataSource(configureHikari(storeName, attributes));
Environment environment = new Environment(storeName, new JdbcTransactionFactory(), dataSource);
sessionFactory = new DefaultSqlSessionFactory(configureMyBatis(environment));
registerCommonTypeHandlers(isContentStore);
if (beanLocator != null) {
// register the appropriate type handlers with the store
beanLocator.watch(TYPE_HANDLER_KEY,
isContentStore ? CONTENT_TYPE_HANDLER_MEDIATOR : CONFIG_TYPE_HANDLER_MEDIATOR, this);
}
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
//通过事务工厂来产生一个事务
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
//生成一个执行器(事务包含在执行器里)
final Executor executor = configuration.newExecutor(tx, execType);
//然后产生一个DefaultSqlSession
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
//如果打开事务出错,则关闭它
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
//最后清空错误上下文
ErrorContext.instance().reset();
}
}
private void environmentsElement(XNode context) throws Exception {
if (context != null) {
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
//循环比较id是否就是指定的environment
if (isSpecifiedEnvironment(id)) {
//7.1事务管理器
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
//7.2数据源
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
DataSource dataSource = dsFactory.getDataSource();
Environment.Builder environmentBuilder = new Environment.Builder(id)
.transactionFactory(txFactory)
.dataSource(dataSource);
configuration.setEnvironment(environmentBuilder.build());
}
}
}
}
@BeforeClass
public static void setup() throws Exception {
DataSource dataSource = BaseDataTest.createBlogDataSource();
BaseDataTest.runScript(dataSource, BaseDataTest.BLOG_DDL);
BaseDataTest.runScript(dataSource, BaseDataTest.BLOG_DATA);
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("Production", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.setLazyLoadingEnabled(true);
configuration.getTypeAliasRegistry().registerAlias(Blog.class);
configuration.getTypeAliasRegistry().registerAlias(Post.class);
configuration.getTypeAliasRegistry().registerAlias(Author.class);
configuration.addMapper(BoundBlogMapper.class);
configuration.addMapper(BoundAuthorMapper.class);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}
@Test
public void testConfiguration() {
UnpooledDataSourceFactory dataSourceFactory = new UnpooledDataSourceFactory();
Properties dataSourceProperties = new Properties();
dataSourceProperties.put("driver", "org.hsqldb.jdbcDriver");
dataSourceProperties.put("url", "jdbc:hsqldb:mem:xml_references");
dataSourceProperties.put("username", "sa");
dataSourceFactory.setProperties(dataSourceProperties);
Environment environment = new Environment("test", new JdbcTransactionFactory(), dataSourceFactory.getDataSource());
Configuration configuration = new Configuration();
configuration.setEnvironment(environment);
configuration.getTypeAliasRegistry().registerAlias(Person.class);
configuration.addMapper(PersonMapper.class);
configuration.addMapper(PersonMapper2.class);
new DefaultSqlSessionFactory(configuration);
}
@Test
public void testGetMessageForEmptyDatabase() throws Exception {
final Environment environment = new Environment("test", new JdbcTransactionFactory(), BaseDataTest.createBlogDataSource());
final Configuration config = new Configuration(environment);
config.addMapper(PostMapper.class);
final SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
final SqlSession session = factory.openSession();
PostMapper mapper = session.getMapper(PostMapper.class);
List<AnnoPost> posts = mapper.getPosts(101);
assertEquals(3,posts.size());
assertEquals(3,posts.get(0).getTags().size());
assertEquals(1,posts.get(1).getTags().size());
assertEquals(0,posts.get(2).getTags().size());
session.close();
}
@BeforeClass
public static void setUp() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:annots", "sa", "");
Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/substitution_in_annots/CreateDB.sql");
ScriptRunner runner = new ScriptRunner(c);
runner.setLogWriter(null);
runner.setErrorLogWriter(null);
runner.runScript(reader);
c.commit();
reader.close();
Configuration configuration = new Configuration();
Environment environment = new Environment("test", new JdbcTransactionFactory(), new UnpooledDataSource("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:annots", null));
configuration.setEnvironment(environment);
configuration.addMapper(SubstitutionInAnnotsMapper.class);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}
private SqlSessionFactory getSqlSessionFactoryWithConstructor() {
UnpooledDataSourceFactory unpooledDataSourceFactory = new UnpooledDataSourceFactory();
Properties properties = new Properties();
properties.setProperty("driver", "org.hsqldb.jdbcDriver");
properties.setProperty("url", "jdbc:hsqldb:mem:extends_with_constructor");
properties.setProperty("username", "sa");
unpooledDataSourceFactory.setProperties(properties);
Environment environment = new Environment("extends_with_constructor", new JdbcTransactionFactory(), unpooledDataSourceFactory.getDataSource());
Configuration configuration = new Configuration();
configuration.setEnvironment(environment);
configuration.addMapper(StudentConstructorMapper.class);
configuration.addMapper(TeacherMapper.class);
configuration.getMappedStatementNames();
configuration.setAutoMappingBehavior(AutoMappingBehavior.NONE);
return new DefaultSqlSessionFactory(configuration);
}
public BaseDb(DataSource ds, Props props, String url) {
this.ds = ds;
this.props = props;
this.dialect = props.getStrVal(PropKey.db_dialect);
String mappersPackageName = getClass().getPackage().getName();
//mybatis
TransactionFactory txFactory = new JdbcTransactionFactory();
Environment environment = new Environment("prod", txFactory, ds);
Configuration config = new Configuration(environment);
config.addMappers(mappersPackageName, BaseMapper.class);
mappers = config.getMapperRegistry().getMappers();
sessionFactory = new SqlSessionFactoryBuilder().build(config);
universal = new UniversalQueries(ds, props, url);
}
private CommitOnCloseSession openCommitOnCloseSession(boolean batch){
ExecutorType executorType = batch? ExecutorType.BATCH : ExecutorType.SIMPLE;
if( ! isSingleTxMode()){
return new CommitOnCloseSession(sessionFactory.openSession(executorType));
}
//SINGLE CONN MODE
Environment env = sessionFactory.getConfiguration().getEnvironment();
DataSource ds = env.getDataSource();
Connection conn = null;
try {
conn = getSingleOrNewConnection(ds);
}catch (Exception e) {
throw new IllegalStateException("can't get conneciton", e);
}
return new CommitOnCloseSession(sessionFactory.openSession(executorType, conn));
}
/**
* 使用DataSource初始化SqlSessionFactory
* @param ds 数据源
*/
public static void initialize(DataSource ds) {
TransactionFactory transactionFactory = new MybatisTransactionFactory();
Environment environment = new Environment("snaker", transactionFactory, ds);
Configuration configuration = new Configuration(environment);
configuration.getTypeAliasRegistry().registerAliases(SCAN_PACKAGE, Object.class);
if (log.isInfoEnabled()) {
Map<String, Class<?>> typeAliases = configuration.getTypeAliasRegistry().getTypeAliases();
for(Entry<String, Class<?>> entry : typeAliases.entrySet()) {
log.info("Scanned class:[name=" + entry.getKey() + ",class=" + entry.getValue().getName() + "]");
}
}
try {
for(String resource : resources) {
InputStream in = Resources.getResourceAsStream(resource);
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, resource, configuration.getSqlFragments());
xmlMapperBuilder.parse();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ErrorContext.instance().reset();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
//通过事务工厂来产生一个事务
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
//生成一个执行器(事务包含在执行器里)
final Executor executor = configuration.newExecutor(tx, execType);
//然后产生一个DefaultSqlSession
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
//如果打开事务出错,则关闭它
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
//最后清空错误上下文
ErrorContext.instance().reset();
}
}
private void environmentsElement(XNode context) throws Exception {
if (context != null) {
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
//循环比较id是否就是指定的environment
if (isSpecifiedEnvironment(id)) {
//7.1事务管理器
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
//7.2数据源
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
DataSource dataSource = dsFactory.getDataSource();
Environment.Builder environmentBuilder = new Environment.Builder(id)
.transactionFactory(txFactory)
.dataSource(dataSource);
configuration.setEnvironment(environmentBuilder.build());
}
}
}
}
@BeforeClass
public static void setup() throws Exception {
DataSource dataSource = BaseDataTest.createBlogDataSource();
BaseDataTest.runScript(dataSource, BaseDataTest.BLOG_DDL);
BaseDataTest.runScript(dataSource, BaseDataTest.BLOG_DATA);
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("Production", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.setLazyLoadingEnabled(true);
configuration.getTypeAliasRegistry().registerAlias(Blog.class);
configuration.getTypeAliasRegistry().registerAlias(Post.class);
configuration.getTypeAliasRegistry().registerAlias(Author.class);
configuration.addMapper(BoundBlogMapper.class);
configuration.addMapper(BoundAuthorMapper.class);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}
@Test
public void testConfiguration() {
UnpooledDataSourceFactory dataSourceFactory = new UnpooledDataSourceFactory();
Properties dataSourceProperties = new Properties();
dataSourceProperties.put("driver", "org.hsqldb.jdbcDriver");
dataSourceProperties.put("url", "jdbc:hsqldb:mem:xml_references");
dataSourceProperties.put("username", "sa");
dataSourceFactory.setProperties(dataSourceProperties);
Environment environment = new Environment("test", new JdbcTransactionFactory(), dataSourceFactory.getDataSource());
Configuration configuration = new Configuration();
configuration.setEnvironment(environment);
configuration.getTypeAliasRegistry().registerAlias(Person.class);
configuration.addMapper(PersonMapper.class);
configuration.addMapper(PersonMapper2.class);
new DefaultSqlSessionFactory(configuration);
}
@Test
public void testGetMessageForEmptyDatabase() throws Exception {
final Environment environment = new Environment("test", new JdbcTransactionFactory(), BaseDataTest.createBlogDataSource());
final Configuration config = new Configuration(environment);
config.addMapper(PostMapper.class);
final SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(config);
final SqlSession session = factory.openSession();
PostMapper mapper = session.getMapper(PostMapper.class);
List<AnnoPost> posts = mapper.getPosts(101);
assertEquals(3,posts.size());
assertEquals(3,posts.get(0).getTags().size());
assertEquals(1,posts.get(1).getTags().size());
assertEquals(0,posts.get(2).getTags().size());
session.close();
}
@BeforeClass
public static void setUp() throws Exception {
Class.forName("org.hsqldb.jdbcDriver");
Connection c = DriverManager.getConnection("jdbc:hsqldb:mem:annots", "sa", "");
Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/substitution_in_annots/CreateDB.sql");
ScriptRunner runner = new ScriptRunner(c);
runner.setLogWriter(null);
runner.setErrorLogWriter(null);
runner.runScript(reader);
c.commit();
reader.close();
Configuration configuration = new Configuration();
Environment environment = new Environment("test", new JdbcTransactionFactory(), new UnpooledDataSource("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:annots", null));
configuration.setEnvironment(environment);
configuration.addMapper(SubstitutionInAnnotsMapper.class);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}
private SqlSessionFactory getSqlSessionFactoryWithConstructor() {
UnpooledDataSourceFactory unpooledDataSourceFactory = new UnpooledDataSourceFactory();
Properties properties = new Properties();
properties.setProperty("driver", "org.hsqldb.jdbcDriver");
properties.setProperty("url", "jdbc:hsqldb:mem:extends_with_constructor");
properties.setProperty("username", "sa");
unpooledDataSourceFactory.setProperties(properties);
Environment environment = new Environment("extends_with_constructor", new JdbcTransactionFactory(), unpooledDataSourceFactory.getDataSource());
Configuration configuration = new Configuration();
configuration.setEnvironment(environment);
configuration.addMapper(StudentConstructorMapper.class);
configuration.addMapper(TeacherMapper.class);
configuration.getMappedStatementNames();
configuration.setAutoMappingBehavior(AutoMappingBehavior.NONE);
return new DefaultSqlSessionFactory(configuration);
}
private void environmentsElement(XNode context) throws Exception {
if (context != null) {
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
if (isSpecifiedEnvironment(id)) {
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
DataSource dataSource = dsFactory.getDataSource();
Environment.Builder environmentBuilder = new Environment.Builder(id)
.transactionFactory(txFactory)
.dataSource(dataSource);
configuration.setEnvironment(environmentBuilder.build());
}
}
}
}
@Autowired
public void configSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
MultiDataSourceTransactionFactory multiDataSourceTransactionFactory = new MultiDataSourceTransactionFactory();
Pair<Field, Object> envFieldBundle = ReflectUtil.getFieldBundlePath(sqlSessionFactory, "configuration.environment");
Environment originEnvironment = (Environment) envFieldBundle.getValue();
Environment environment = new Environment(originEnvironment.getId(), multiDataSourceTransactionFactory, originEnvironment.getDataSource());
Pair<Field, Object> confFieldBundle = ReflectUtil.getFieldBundlePath(sqlSessionFactory, "configuration");
Object configuration = confFieldBundle.getValue();
ReflectUtil.invokeMethod(configuration, "setEnvironment", new Class[]{Environment.class}, environment);
}
public IDAllocDaoImpl(DataSource dataSource) {
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(IDAllocMapper.class);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
}
public Configuration initMybatisConfiguration(Environment environment, Reader reader, Properties properties) {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
Configuration configuration = parser.getConfiguration();
if (databaseType != null) {
configuration.setDatabaseId(databaseType);
}
configuration.setEnvironment(environment);
initCustomMybatisMappers(configuration);
configuration = parseMybatisConfiguration(configuration, parser);
return configuration;
}
protected Configuration initMybatisConfiguration(Environment environment, Reader reader, Properties properties) {
XMLConfigBuilder parser = new XMLConfigBuilder(reader,"", properties);
Configuration configuration = parser.getConfiguration();
configuration.setEnvironment(environment);
initMybatisTypeHandlers(configuration);
initCustomMybatisMappers(configuration);
configuration = parseMybatisConfiguration(configuration, parser);
return configuration;
}
public Configuration initMybatisConfiguration(Environment environment, Reader reader, Properties properties) {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, "", properties);
Configuration configuration = parser.getConfiguration();
if (databaseType != null) {
configuration.setDatabaseId(databaseType);
}
configuration.setEnvironment(environment);
initCustomMybatisMappers(configuration);
configuration = parseMybatisConfiguration(configuration, parser);
return configuration;
}
public static SqlSession createSqlSession(DataSource dataSource) {
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("test", transactionFactory, dataSource);
Configuration config = new Configuration();
config.setCacheEnabled(false);
config.addMapper(CategoryMapper.class);
config.setEnvironment(environment);
SqlSessionFactory sessionFactory = new DefaultSqlSessionFactory(config);
return sessionFactory.openSession();
}