List of usage examples for org.springframework.jdbc.datasource DataSourceUtils getConnection
public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException
From source file:org.mybatis.spring.transaction.SpringManagedTransaction.java
/** * Gets a connection from Spring transaction manager and discovers if this * {@code Transaction} should manage connection or let it to Spring. * <p>/*from ww w . j a v a 2 s. com*/ * It also reads autocommit setting because when using Spring Transaction MyBatis * thinks that autocommit is always false and will always call commit/rollback * so we need to no-op that calls. */ private void openConnection() throws SQLException { this.connection = DataSourceUtils.getConnection(this.dataSource); this.autoCommit = this.connection.getAutoCommit(); this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource); if (LOGGER.isDebugEnabled()) { LOGGER.debug("JDBC Connection [" + this.connection + "] will" + (this.isConnectionTransactional ? " " : " not ") + "be managed by Spring"); } }
From source file:org.opensprout.osaf.test.ApplicationContextTestBase.java
private void insertData(String fileSource, DataType type, DatabaseOperation operation) throws Exception { InputStream sourceStream = new ClassPathResource(fileSource, getClass()).getInputStream(); IDataSet dataset = null;//w w w .j a va 2 s . c om if (type == DataType.EXCEL) { dataset = new XlsDataSet(sourceStream); } else if (type == DataType.FLATXML) { dataset = new FlatXmlDataSet(sourceStream); } operation.execute(new DatabaseConnection(DataSourceUtils.getConnection(dataSource)), dataset); }
From source file:io.kahu.hawaii.util.call.sql.AbortableQuery.java
@Override protected void executeInternally(ResponseHandler responseHandler, Response response) throws ServerException { SqlParameterSource paramSource = new MapSqlParameterSource(params); PreparedStatementCreator psc = getPreparedStatementCreator(sql, paramSource); Connection connection = DataSourceUtils.getConnection(dataSource); try {// w w w.j a va 2 s . c o m preparedStatement = psc.createPreparedStatement(connection); switch (callType) { case INSERT: preparedStatement.executeUpdate(); new UpdateIdResponseHandler().addToResponse(preparedStatement, response); break; case DELETE: // fall though case UPDATE: response.set(preparedStatement.executeUpdate()); break; case SELECT: ResultSet resultSet = preparedStatement.executeQuery(); responseHandler.addToResponse(resultSet, response); break; default: throw new ServerException(ServerError.ILLEGAL_ARGUMENT, "Unknown call type '" + callType + "'."); } } catch (SQLException e) { try { connection.rollback(); } catch (Throwable t) { // } if (!aborted) { response.setStatus(ResponseStatus.BACKEND_FAILURE, e); } throw new ServerException(ServerError.UNEXPECTED_EXCEPTION, e); } finally { DataSourceUtils.releaseConnection(connection, dataSource); } }
From source file:org.grails.orm.hibernate.support.HibernateDialectDetectorFactoryBean.java
public void afterPropertiesSet() throws MetaDataAccessException { Assert.notNull(dataSource, "Data source is not set!"); Assert.notNull(vendorNameDialectMappings, "Vendor name/dialect mappings are not set!"); Connection connection = null; String dbName = (String) JdbcUtils.extractDatabaseMetaData(dataSource, "getDatabaseProductName"); try {/*from ww w .j a va2s . co m*/ connection = DataSourceUtils.getConnection(dataSource); try { final DialectFactory dialectFactory = createDialectFactory(); final Connection finalConnection = connection; DialectResolutionInfoSource infoSource = new DialectResolutionInfoSource() { @Override public DialectResolutionInfo getDialectResolutionInfo() { try { return new DatabaseMetaDataDialectResolutionInfoAdapter(finalConnection.getMetaData()); } catch (SQLException e) { throw new CouldNotDetermineHibernateDialectException( "Could not determine Hibernate dialect", e); } } }; hibernateDialect = dialectFactory.buildDialect(hibernateProperties, infoSource); hibernateDialectClassName = hibernateDialect.getClass().getName(); } catch (HibernateException e) { hibernateDialectClassName = vendorNameDialectMappings.getProperty(dbName); } if (!StringUtils.hasText(hibernateDialectClassName)) { throw new CouldNotDetermineHibernateDialectException( "Could not determine Hibernate dialect for database name [" + dbName + "]!"); } } finally { DataSourceUtils.releaseConnection(connection, dataSource); } }
From source file:net.noday.core.dao.AppDao.java
public App getAppConfig() { List<String> tables = jdbc.queryForList("show tables", String.class); Connection conn = DataSourceUtils.getConnection(jdbc.getDataSource()); try {// ww w . j a v a2s .c o m conn.setAutoCommit(false); if (tables == null || tables.size() == 0 || !tables.contains("app_config")) { initDB(); } else { String version = jdbc.queryForObject("select a.version from app_config a limit 1", String.class); if (!"1.1".equalsIgnoreCase(version)) { updateDB("1_1"); } } conn.commit(); } catch (DataAccessException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } String sql = "select * from app_config limit 1"; App cfg = jdbc.queryForObject(sql, new BeanPropertyRowMapper<App>(App.class)); if (cfg == null) { throw new AppStartupException("??"); } return cfg; }
From source file:com.bluexml.side.Integration.alfresco.sql.synchronization.schemaManagement.SchemaCreation.java
private void createFromModel(QName modelName) { if (ready) {//from ww w . ja va2 s. c om Connection connection = DataSourceUtils.getConnection(dataSource); List<CreateTableStatement> createStatements = doCreateStatement(modelName); CheckTableStatus checkTableStatus = doCheckStatus(createStatements, connection); statusByModel.put(modelName, checkTableStatus); if (checkTableStatus == CheckTableStatus.CREATE_TABLES) { boolean creationSuccess = doExecuteCreateStatements(createStatements, connection); if (!creationSuccess) { logger.error("Creation of tables failed"); ready = false; } DataSourceUtils.releaseConnection(connection, dataSource); } else { if (logger.isDebugEnabled()) logger.debug("Creation of model \"" + modelName + "\" was not performed since the previous process marked the schema as not ready or creation has yet be done"); } } }
From source file:com.healthcit.cacure.test.DataSetTestExecutionListener.java
public void beforeTestMethod(TestContext testContext) throws Exception { // Determine if a dataset should be loaded, from where, and extract any // special configuration. Configuration configuration = determineConfiguration(testContext.getTestClass(), testContext.getTestMethod()); if (configuration == null) return;/*from w w w . j a v a 2s .co m*/ SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken( configuration.getUserName(), configuration.getUserPassword())); if (configuration.getLocation() == null) return; configurationCache.put(testContext.getTestMethod(), configuration); // Find a single, unambiguous data source. DataSource dataSource = lookupDataSource(testContext); // Fetch a connection from the data source, using an existing one if we're // already participating in a transaction. Connection connection = DataSourceUtils.getConnection(dataSource); configuration.setConnectionTransactional(DataSourceUtils.isConnectionTransactional(connection, dataSource)); // Load the data set. loadData(configuration, connection); }
From source file:org.dalesbred.integration.spring.SpringTransactionManager.java
private <T> T execute(@NotNull TransactionCallback<T> callback, @NotNull Dialect dialect, @NotNull DefaultTransactionDefinition df) { TransactionTemplate tt = new TransactionTemplate(platformTransactionManager, df); return tt.execute(status -> { try {// www . java2 s . c o m Connection connection = DataSourceUtils.getConnection(dataSource); try { return callback.execute(new SpringTransactionContext(status, connection)); } finally { DataSourceUtils.releaseConnection(connection, dataSource); } } catch (SQLException e) { throw dialect.convertException(e); } }); }