List of usage examples for org.apache.ibatis.mapping Environment Environment
public Environment(String id, TransactionFactory transactionFactory, DataSource dataSource)
From source file:org.mybatis.spring.mapper.MapperFactoryBeanTest.java
License:Apache License
@Test(expected = TransientDataAccessResourceException.class) public void testNonSpringTxMgrWithTx() throws Exception { Environment original = sqlSessionFactory.getConfiguration().getEnvironment(); Environment nonSpring = new Environment("non-spring", new JdbcTransactionFactory(), dataSource); sqlSessionFactory.getConfiguration().setEnvironment(nonSpring); TransactionStatus status = null;/* www.j a v a 2 s .c om*/ try { status = txManager.getTransaction(new DefaultTransactionDefinition()); find(); fail("should not be able to get an SqlSession using non-Spring tx manager when there is an active Spring tx"); } finally { // rollback required to close connection txManager.rollback(status); sqlSessionFactory.getConfiguration().setEnvironment(original); } }
From source file:org.mybatis.spring.mapper.MapperFactoryBeanTest.java
License:Apache License
@Test public void testNonSpringWithTx() throws Exception { Environment original = sqlSessionFactory.getConfiguration().getEnvironment(); MockDataSource mockDataSource = new MockDataSource(); mockDataSource.setupConnection(createMockConnection()); Environment nonSpring = new Environment("non-spring", new JdbcTransactionFactory(), mockDataSource); sqlSessionFactory.getConfiguration().setEnvironment(nonSpring); SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory); TransactionStatus status = null;/* w w w . j a va2 s.c o m*/ try { status = txManager.getTransaction(new DefaultTransactionDefinition()); find(sqlSessionTemplate); txManager.commit(status); // txManager still uses original connection assertCommit(); assertSingleConnection(); // SqlSessionTemplate uses its own connection MockConnection mockConnection = (MockConnection) mockDataSource.getConnection(); assertEquals("should call commit on Connection", 1, mockConnection.getNumberCommits()); assertEquals("should not call rollback on Connection", 0, mockConnection.getNumberRollbacks()); assertCommitSession(); } finally { sqlSessionFactory.getConfiguration().setEnvironment(original); } }
From source file:org.mybatis.spring.MyBatisSpringTest.java
License:Apache License
@Test public void testWithNonSpringTransactionFactory() { Environment original = sqlSessionFactory.getConfiguration().getEnvironment(); Environment nonSpring = new Environment("non-spring", new JdbcTransactionFactory(), dataSource); sqlSessionFactory.getConfiguration().setEnvironment(nonSpring); try {//from ww w . ja v a2 s.c om session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session.getMapper(TestMapper.class).findTest(); SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); // users need to manually call commit, rollback and close, just like with normal MyBatis // API usage assertNoCommit(); assertSingleConnection(); } finally { sqlSessionFactory.getConfiguration().setEnvironment(original); } }
From source file:org.mybatis.spring.MyBatisSpringTest.java
License:Apache License
@Test(expected = TransientDataAccessResourceException.class) public void testNonSpringTxFactoryWithTx() throws Exception { Environment original = sqlSessionFactory.getConfiguration().getEnvironment(); Environment nonSpring = new Environment("non-spring", new JdbcTransactionFactory(), dataSource); sqlSessionFactory.getConfiguration().setEnvironment(nonSpring); TransactionStatus status = null;/* ww w . j ava 2 s. co m*/ try { status = txManager.getTransaction(new DefaultTransactionDefinition()); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); fail("should not be able to get an SqlSession using non-Spring tx manager when there is an active Spring tx"); } finally { // rollback required to close connection txManager.rollback(status); sqlSessionFactory.getConfiguration().setEnvironment(original); } }
From source file:org.mybatis.spring.MyBatisSpringTest.java
License:Apache License
@Test public void testNonSpringTxFactoryNonSpringDSWithTx() throws java.sql.SQLException { Environment original = sqlSessionFactory.getConfiguration().getEnvironment(); MockDataSource mockDataSource = new MockDataSource(); mockDataSource.setupConnection(createMockConnection()); Environment nonSpring = new Environment("non-spring", new JdbcTransactionFactory(), mockDataSource); sqlSessionFactory.getConfiguration().setEnvironment(nonSpring); TransactionStatus status = null;//from ww w.ja va2s .c o m try { status = txManager.getTransaction(new DefaultTransactionDefinition()); session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session.commit(); session.close(); txManager.commit(status); // txManager still uses original connection assertCommit(); assertSingleConnection(); // SqlSession uses its own connection // that connection will not have commited since no SQL was executed by the session MockConnection mockConnection = (MockConnection) mockDataSource.getConnection(); assertEquals("should call commit on Connection", 0, mockConnection.getNumberCommits()); assertEquals("should not call rollback on Connection", 0, mockConnection.getNumberRollbacks()); assertCommitSession(); } finally { SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); sqlSessionFactory.getConfiguration().setEnvironment(original); } }
From source file:org.mybatis.spring.MyBatisSpringTest.java
License:Apache License
@Test public void testWithJtaTxManagerAndNonSpringTxManager() throws java.sql.SQLException { Environment original = sqlSessionFactory.getConfiguration().getEnvironment(); MockDataSource mockDataSource = new MockDataSource(); mockDataSource.setupConnection(createMockConnection()); Environment nonSpring = new Environment("non-spring", new ManagedTransactionFactory(), mockDataSource); sqlSessionFactory.getConfiguration().setEnvironment(nonSpring); JtaTransactionManager jtaManager = new JtaTransactionManager(new MockUserTransaction()); DefaultTransactionDefinition txDef = new DefaultTransactionDefinition(); txDef.setPropagationBehaviorName("PROPAGATION_REQUIRED"); TransactionStatus status = jtaManager.getTransaction(txDef); try {/*from w ww.ja v a 2 s. c o m*/ session = SqlSessionUtils.getSqlSession(sqlSessionFactory); session.getMapper(TestMapper.class).findTest(); // Spring is not managing SqlSession, so commit is needed session.commit(true); SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); jtaManager.commit(status); // assume a real JTA tx would enlist and commit the JDBC connection assertNoCommitJdbc(); assertCommitSession(); MockConnection mockConnection = (MockConnection) mockDataSource.getConnection(); assertEquals("should call commit on Connection", 0, mockConnection.getNumberCommits()); assertEquals("should not call rollback on Connection", 0, mockConnection.getNumberRollbacks()); assertEquals("should not call DataSource.getConnection()", 0, dataSource.getConnectionCount()); } finally { SqlSessionUtils.closeSqlSession(session, sqlSessionFactory); sqlSessionFactory.getConfiguration().setEnvironment(original); // null the connection since it was not used // this avoids failing in validateConnectionClosed() connection = null; } }
From source file:org.mybatis.spring.SqlSessionFactoryBean.java
License:Apache License
/** * Build a {@code SqlSessionFactory} instance. * * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a * {@code SqlSessionFactory} instance based on an Reader. * * @return SqlSessionFactory// ww w.ja v a 2 s.com * @throws IOException if loading the config file failed */ protected SqlSessionFactory buildSqlSessionFactory() throws IOException { Configuration configuration; XMLConfigBuilder xmlConfigBuilder = null; if (this.configLocation != null) { xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties); configuration = xmlConfigBuilder.getConfiguration(); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Property 'configLocation' not specified, using default MyBatis Configuration"); } configuration = new Configuration(); configuration.setVariables(this.configurationProperties); } if (this.objectFactory != null) { configuration.setObjectFactory(this.objectFactory); } if (this.objectWrapperFactory != null) { configuration.setObjectWrapperFactory(this.objectWrapperFactory); } if (hasLength(this.typeAliasesPackage)) { String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeAliasPackageArray) { configuration.getTypeAliasRegistry().registerAliases(packageToScan, typeAliasesSuperType == null ? Object.class : typeAliasesSuperType); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases"); } } } if (!isEmpty(this.typeAliases)) { for (Class<?> typeAlias : this.typeAliases) { configuration.getTypeAliasRegistry().registerAlias(typeAlias); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registered type alias: '" + typeAlias + "'"); } } } if (!isEmpty(this.plugins)) { for (Interceptor plugin : this.plugins) { configuration.addInterceptor(plugin); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registered plugin: '" + plugin + "'"); } } } if (hasLength(this.typeHandlersPackage)) { String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeHandlersPackageArray) { configuration.getTypeHandlerRegistry().register(packageToScan); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Scanned package: '" + packageToScan + "' for type handlers"); } } } if (!isEmpty(this.typeHandlers)) { for (TypeHandler<?> typeHandler : this.typeHandlers) { configuration.getTypeHandlerRegistry().register(typeHandler); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registered type handler: '" + typeHandler + "'"); } } } if (xmlConfigBuilder != null) { try { xmlConfigBuilder.parse(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parsed configuration file: '" + this.configLocation + "'"); } } catch (Exception ex) { throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex); } finally { ErrorContext.instance().reset(); } } if (this.transactionFactory == null) { this.transactionFactory = new SpringManagedTransactionFactory(); } configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource)); if (this.databaseIdProvider != null) { try { configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource)); } catch (SQLException e) { throw new NestedIOException("Failed getting a databaseId", e); } } if (!isEmpty(this.mapperLocations)) { for (Resource mapperLocation : this.mapperLocations) { if (mapperLocation == null) { continue; } try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception e) { throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e); } finally { ErrorContext.instance().reset(); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'"); } } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found"); } } return this.sqlSessionFactoryBuilder.build(configuration); }
From source file:org.mybatis.spring.utils.SqlSessionFactoryBean.java
License:Apache License
/** * Build a {@code SqlSessionFactory} instance. * /*from w w w . j av a 2 s . c o m*/ * The default implementation uses the standard MyBatis * {@code XMLConfigBuilder} API to build a {@code SqlSessionFactory} * instance based on an Reader. * * @return SqlSessionFactory * @throws IOException * if loading the config file failed */ protected SqlSessionFactory buildSqlSessionFactory() throws IOException { Configuration configuration; XMLConfigBuilder xmlConfigBuilder = null; if (this.configLocation != null) { xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties); configuration = xmlConfigBuilder.getConfiguration(); } else { if (logger.isDebugEnabled()) { logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration"); } configuration = new Configuration(); configuration.setVariables(this.configurationProperties); } if (this.objectFactory != null) { configuration.setObjectFactory(this.objectFactory); } if (this.objectWrapperFactory != null) { configuration.setObjectWrapperFactory(this.objectWrapperFactory); } if (hasLength(this.typeAliasesPackage)) { String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeAliasPackageArray) { configuration.getTypeAliasRegistry().registerAliases(packageToScan, typeAliasesSuperType == null ? Object.class : typeAliasesSuperType); if (logger.isDebugEnabled()) { logger.debug("Scanned package: '" + packageToScan + "' for aliases"); } } } if (!isEmpty(this.typeAliases)) { for (Class<?> typeAlias : this.typeAliases) { configuration.getTypeAliasRegistry().registerAlias(typeAlias); if (logger.isDebugEnabled()) { logger.debug("Registered type alias: '" + typeAlias + "'"); } } } if (!isEmpty(this.plugins)) { for (Interceptor plugin : this.plugins) { configuration.addInterceptor(plugin); if (logger.isDebugEnabled()) { logger.debug("Registered plugin: '" + plugin + "'"); } } } if (hasLength(this.typeHandlersPackage)) { String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeHandlersPackageArray) { configuration.getTypeHandlerRegistry().register(packageToScan); if (logger.isDebugEnabled()) { logger.debug("Scanned package: '" + packageToScan + "' for type handlers"); } } } if (!isEmpty(this.typeHandlers)) { for (TypeHandler<?> typeHandler : this.typeHandlers) { configuration.getTypeHandlerRegistry().register(typeHandler); if (logger.isDebugEnabled()) { logger.debug("Registered type handler: '" + typeHandler + "'"); } } } if (xmlConfigBuilder != null) { try { xmlConfigBuilder.parse(); if (logger.isDebugEnabled()) { logger.debug("Parsed configuration file: '" + this.configLocation + "'"); } } catch (Exception ex) { throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex); } finally { ErrorContext.instance().reset(); } } if (this.transactionFactory == null) { this.transactionFactory = new SpringManagedTransactionFactory(); } Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource); configuration.setEnvironment(environment); if (this.databaseIdProvider != null) { try { configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource)); } catch (SQLException e) { throw new NestedIOException("Failed getting a databaseId", e); } } // TODO location ?xml?? String location = null; if (!isEmpty(this.mapperLocations)) { for (Resource mapperLocation : this.mapperLocations) { if (location == null) { location = mapperLocation.toString(); } if (mapperLocation == null) { continue; } try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception e) { e.printStackTrace(); // throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e); } finally { ErrorContext.instance().reset(); } if (logger.isDebugEnabled()) { logger.debug("Parsed mapper file: '" + mapperLocation + "'"); } } } else { if (logger.isDebugEnabled()) { logger.debug("Property 'mapperLocations' was not specified or no matching resources found"); } } // TODO sqlsession? new org.mybatis.spring.utils.Runnable(location, configuration).run(); return this.sqlSessionFactoryBuilder.build(configuration); }
From source file:org.neo4j.jdbc.example.mybatis.MybatisTest.java
License:Apache License
protected void buildMybatisConfiguration(String protocol, String host, int port) { DataSource dataSource = new UnpooledDataSource("org.neo4j.jdbc.Driver", "jdbc:neo4j:" + protocol + "://" + host + ":" + port + "?noSsl", null); TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); Configuration configuration = new Configuration(environment); configuration.getMapperRegistry().addMapper(ActorMapper.class); configuration.addLoadedResource("org/neo4j/jdbc/example/mybatis/mapper/ActorMapper.xml"); ConnectionFactory.getSqlSessionFactory(configuration); }
From source file:org.pssframework.dao.SqlSessionFactoryFactoryBean.java
License:Open Source License
private SqlSessionFactory createSqlSessionFactory() throws IOException { Reader reader = new InputStreamReader(getConfigLocation().getInputStream()); try {/* w w w . ja v a2s . c o m*/ SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); Configuration conf = sqlSessionFactory.getConfiguration(); if (dataSource != null) { DataSource dataSourceToUse = this.dataSource; if (this.useTransactionAwareDataSource && !(this.dataSource instanceof TransactionAwareDataSourceProxy)) { dataSourceToUse = new TransactionAwareDataSourceProxy(this.dataSource); } conf.setEnvironment( new Environment("development", new ManagedTransactionFactory(), dataSourceToUse)); sqlSessionFactory = new SqlSessionFactoryBuilder().build(conf); } if (mapperLocations != null) { Map<String, XNode> sqlFragments = new HashMap<String, XNode>(); for (Resource r : mapperLocations) { logger.info("Loading iBatis3 mapper xml from file[" + r.getFile().getAbsolutePath() + "]"); Reader mapperReader = new InputStreamReader(r.getInputStream()); try { XMLMapperBuilder mapperBuilder = new XMLMapperBuilder(mapperReader, conf, r.getFile().getAbsolutePath(), sqlFragments); mapperBuilder.parse(); } finally { mapperReader.close(); } } } return sqlSessionFactory; } finally { reader.close(); } }