Example usage for org.apache.ibatis.mapping Environment getDataSource

List of usage examples for org.apache.ibatis.mapping Environment getDataSource

Introduction

In this page you can find the example usage for org.apache.ibatis.mapping Environment getDataSource.

Prototype

public DataSource getDataSource() 

Source Link

Usage

From source file:org.hsweb.web.mybatis.dynamic.DynamicSqlSessionFactory.java

License:Apache License

private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,
        boolean autoCommit) {
    Transaction tx = null;/*  w w  w .  j  ava2 s.c o  m*/
    try {
        final Environment environment = getConfiguration().getEnvironment();
        final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
        DataSource ds = DataSourceHolder.getActiveSource();
        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();
    }
}

From source file:org.hswebframework.web.dao.mybatis.dynamic.DynamicSqlSessionFactory.java

License:Apache License

@SuppressWarnings("all")
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,
        boolean autoCommit) {
    Transaction tx = null;//from   w w w  . ja  v  a 2 s  .  c  om
    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();
    }
}

From source file:org.mybatis.guice.AbstractGuiceTestExtension.java

License:Apache License

public AbstractGuiceTestExtension() throws SQLException {
    final Contact contact = new Contact();
    contact.setFirstName("John");
    contact.setLastName("Doe");
    contact.setCreated(new CustomType(currentTimeMillis()));
    contact.setAddress(null);//from w  w w  .  ja va2s.c  o m

    final Contact contactWithAddress = new Contact();
    contactWithAddress.setFirstName("John");
    contactWithAddress.setLastName("Doe");
    contactWithAddress.setCreated(new CustomType(currentTimeMillis()));

    final Address address = new Address();
    address.setNumber(1234);
    address.setStreet("Elm street");
    contactWithAddress.setAddress(address);

    final Counter counter = new Counter();

    // bindings
    final List<Module> modules = this.createMyBatisModule();
    modules.add(new Module() {
        @Override
        public void configure(Binder binder) {
            bindProperties(binder, createTestProperties());
            binder.bind(Contact.class).toInstance(contact);
            binder.bind(Contact.class).annotatedWith(named("contactWithAddress"))
                    .toInstance(contactWithAddress);
            binder.bind(Counter.class).toInstance(counter);
        }
    });
    this.injector = createInjector(modules);

    // prepare the test db
    final Environment environment = this.injector.getInstance(SqlSessionFactory.class).getConfiguration()
            .getEnvironment();
    final DataSource dataSource = environment.getDataSource();
    final ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
    runner.setAutoCommit(true);
    runner.setStopOnError(true);
    runner.runScript(new StringReader("DROP TABLE IF EXISTS contact;"
            + "CREATE TABLE contact (id int GENERATED BY DEFAULT AS IDENTITY (START WITH 1), "
            + "first_name VARCHAR(20) NOT NULL, " + "last_name VARCHAR(20) NOT NULL, " + "created TIMESTAMP, "
            + "address VARCHAR(100) DEFAULT NULL) ;"));
    runner.closeConnection();
}

From source file:org.mybatis.guice.AbstractGuiceTestRunner.java

License:Apache License

public AbstractGuiceTestRunner(Class<?> klass) throws InitializationError {
    super(klass);

    try {//from   w w  w .j av  a 2 s .  co  m
        final Contact contact = new Contact();
        contact.setFirstName("John");
        contact.setLastName("Doe");
        contact.setCreated(new CustomType(currentTimeMillis()));
        contact.setAddress(null);

        final Contact contactWithAddress = new Contact();
        contactWithAddress.setFirstName("John");
        contactWithAddress.setLastName("Doe");
        contactWithAddress.setCreated(new CustomType(currentTimeMillis()));

        Address address = new Address();
        address.setNumber(1234);
        address.setStreet("Elm street");
        contactWithAddress.setAddress(address);

        final Counter counter = new Counter();

        // bindings
        List<Module> modules = this.createMyBatisModule();
        modules.add(new Module() {
            public void configure(Binder binder) {
                bindProperties(binder, createTestProperties());
                binder.bind(Contact.class).toInstance(contact);
                binder.bind(Contact.class).annotatedWith(named("contactWithAddress"))
                        .toInstance(contactWithAddress);
                binder.bind(Counter.class).toInstance(counter);
            }
        });
        this.injector = createInjector(modules);

        // prepare the test db
        Environment environment = this.injector.getInstance(SqlSessionFactory.class).getConfiguration()
                .getEnvironment();
        DataSource dataSource = environment.getDataSource();
        ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
        runner.setAutoCommit(true);
        runner.setStopOnError(true);
        runner.runScript(new StringReader("DROP TABLE IF EXISTS contact;"
                + "CREATE TABLE contact (id int GENERATED BY DEFAULT AS IDENTITY (START WITH 1), "
                + "first_name VARCHAR(20) NOT NULL, " + "last_name VARCHAR(20) NOT NULL, "
                + "created TIMESTAMP, " + "address VARCHAR(100) DEFAULT NULL) ;"));
        runner.closeConnection();
    } catch (Exception e) {
        throw new InitializationError(e);
    }
}

From source file:org.mybatis.guice.environment.EnvironmentProviderTest.java

License:Apache License

@Test
public void get() {
    Environment environment = environmentProvider.get();
    assertEquals(id, environment.getId());
    assertEquals(dataSource, environment.getDataSource());
    assertEquals(transactionFactory, environment.getTransactionFactory());
}

From source file:org.mybatis.guice.nestedtx.NestedTxTest.java

License:Apache License

@BeforeEach
public void setup() throws Exception {
    injector = Guice.createInjector(new MyBatisModule() {
        @Override//from  www  .  ja v  a2  s. co m
        protected void initialize() {
            bindDataSourceProviderType(PooledDataSourceProvider.class);
            bindTransactionFactoryType(JdbcTransactionFactory.class);

            install(JdbcHelper.HSQLDB_IN_MEMORY_NAMED);

            Properties connectionProps = new Properties();
            connectionProps.setProperty("mybatis.environment.id", "jdbc");
            connectionProps.setProperty("JDBC.username", "sa");
            connectionProps.setProperty("JDBC.password", "");
            connectionProps.setProperty("JDBC.autoCommit", "false");

            Names.bindProperties(binder(), connectionProps);

            addMapperClass(NestedTxMapper.class);
            bind(NestedTxService.class);
        }
    });

    // prepare the test db
    Environment environment = this.injector.getInstance(SqlSessionFactory.class).getConfiguration()
            .getEnvironment();
    DataSource dataSource = environment.getDataSource();
    ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
    runner.setAutoCommit(true);
    runner.setStopOnError(true);
    runner.runScript(getResourceAsReader("org/mybatis/guice/nestedtx/setupdb.sql"));
    runner.closeConnection();

    service = injector.getInstance(NestedTxService.class);
}

From source file:org.mybatis.guice.sample.SampleBasicTest.java

License:Apache License

@BeforeEach
public void setupMyBatisGuice() throws Exception {

    // bindings// w ww  . ja  va 2  s .  c o m
    this.injector = createInjector(new MyBatisModule() {

        @Override
        protected void initialize() {
            install(JdbcHelper.HSQLDB_IN_MEMORY_NAMED);

            bindDataSourceProviderType(PooledDataSourceProvider.class);
            bindTransactionFactoryType(JdbcTransactionFactory.class);
            addMapperClass(UserMapper.class);

            bindProperties(binder(), createTestProperties());
            bind(FooService.class).to(FooServiceMapperImpl.class);
        }

    });

    // prepare the test db
    Environment environment = this.injector.getInstance(SqlSessionFactory.class).getConfiguration()
            .getEnvironment();
    DataSource dataSource = environment.getDataSource();
    ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
    runner.setAutoCommit(true);
    runner.setStopOnError(true);
    runner.runScript(getResourceAsReader("org/mybatis/guice/sample/db/database-schema.sql"));
    runner.runScript(getResourceAsReader("org/mybatis/guice/sample/db/database-test-data.sql"));
    runner.closeConnection();

    this.fooService = this.injector.getInstance(FooService.class);
}

From source file:org.mybatis.guice.sample.SampleSqlSessionTest.java

License:Apache License

@BeforeEach
public void setupMyBatisGuice() throws Exception {

    // bindings//from   w  w  w . j  a v a 2  s. c  o m
    List<Module> modules = this.createMyBatisModule();
    this.injector = Guice.createInjector(modules);

    // prepare the test db
    Environment environment = this.injector.getInstance(SqlSessionFactory.class).getConfiguration()
            .getEnvironment();
    DataSource dataSource = environment.getDataSource();
    ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
    runner.setAutoCommit(true);
    runner.setStopOnError(true);
    runner.runScript(getResourceAsReader("org/mybatis/guice/sample/db/database-schema.sql"));
    runner.runScript(getResourceAsReader("org/mybatis/guice/sample/db/database-test-data.sql"));
    runner.closeConnection();

    this.fooService = this.injector.getInstance(FooService.class);
}

From source file:org.mybatis.guice.sample.SampleTestBase.java

License:Apache License

private void createTestDb(Injector injector) throws IOException, SQLException {
    // prepare the test db
    Environment environment = injector.getInstance(SqlSessionFactory.class).getConfiguration().getEnvironment();
    DataSource dataSource = environment.getDataSource();

    ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
    runner.setAutoCommit(true);//from w ww. j  a va 2s. c  o  m
    runner.setStopOnError(true);
    runner.runScript(getResourceAsReader("org/mybatis/guice/sample/db/database-schema.sql"));
    runner.runScript(getResourceAsReader("org/mybatis/guice/sample/db/database-test-data.sql"));
    runner.closeConnection();
}

From source file:org.mybatis.spring.SqlSessionUtils.java

License:Apache License

/**
 * Register session holder if synchronization is active (i.e. a Spring TX is active).
 *
 * Note: The DataSource used by the Environment should be synchronized with the
 * transaction either through DataSourceTxMgr or another tx synchronization.
 * Further assume that if an exception is thrown, whatever started the transaction will
 * handle closing / rolling back the Connection associated with the SqlSession.
 * //w  ww  .j a  v  a2s  .  c  o m
 * @param sessionFactory sqlSessionFactory used for registration.
 * @param executorType executorType used for registration.
 * @param exceptionTranslator persistenceExceptionTranslater used for registration.
 * @param session sqlSession used for registration.
 */
private static void registerSessionHolder(SqlSessionFactory sessionFactory, ExecutorType executorType,
        PersistenceExceptionTranslator exceptionTranslator, SqlSession session) {
    SqlSessionHolder holder;
    if (TransactionSynchronizationManager.isSynchronizationActive()) {
        Environment environment = sessionFactory.getConfiguration().getEnvironment();

        if (environment.getTransactionFactory() instanceof SpringManagedTransactionFactory) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Registering transaction synchronization for SqlSession [" + session + "]");
            }

            holder = new SqlSessionHolder(session, executorType, exceptionTranslator);
            TransactionSynchronizationManager.bindResource(sessionFactory, holder);
            TransactionSynchronizationManager
                    .registerSynchronization(new SqlSessionSynchronization(holder, sessionFactory));
            holder.setSynchronizedWithTransaction(true);
            holder.requested();
        } else {
            if (TransactionSynchronizationManager.getResource(environment.getDataSource()) == null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("SqlSession [" + session
                            + "] was not registered for synchronization because DataSource is not transactional");
                }
            } else {
                throw new TransientDataAccessResourceException(
                        "SqlSessionFactory must be using a SpringManagedTransactionFactory in order to use Spring transaction synchronization");
            }
        }
    } else {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("SqlSession [" + session
                    + "] was not registered for synchronization because synchronization is not active");
        }
    }
}