Java Code Examples for org.springframework.jdbc.datasource.DataSourceUtils.getConnection()

The following are Jave code examples for showing how to use getConnection() of the org.springframework.jdbc.datasource.DataSourceUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: EasyTransaction   File: DefaultTransStatusLoggerImpl.java   View Source Code Vote up 6 votes
@Override
public void writeExecuteFlag(String appId, String busCode, String trxId, String pAppId, String pBusCode, String pTrxId, int status) {
	
	Connection connection = DataSourceUtils.getConnection(selctor.selectDataSource(appId, busCode, trxId));
	
	try {
		PreparedStatement prepareStatement = connection.prepareStatement("INSERT INTO `executed_trans` (`app_id`, `bus_code`, `trx_id`,`p_app_id`, `p_bus_code`, `p_trx_id`,`status`) VALUES ( ?, ?, ?, ?, ?, ?, ?);");
		prepareStatement.setString(1, appId);
		prepareStatement.setString(2, busCode);
		prepareStatement.setString(3, trxId);
		prepareStatement.setString(4, pAppId);
		prepareStatement.setString(5, pBusCode);
		prepareStatement.setString(6, pTrxId);
		prepareStatement.setInt(7, status);
		
		int executeUpdate = prepareStatement.executeUpdate();
		if(executeUpdate != 1){
			throw new RuntimeException(String.format("insert count(%s) Error!%s %s %s %s %s %s %s", executeUpdate,appId,busCode,trxId,pAppId,pBusCode,pTrxId,status));
		}
	} catch (SQLException e) {
		throw new RuntimeException("insert Sql failed,check whether the same transaction has been executed?",e);
	}
}
 
Example 2
Project: bdf2   File: DbCommonServiceImpl.java   View Source Code Vote up 6 votes
public List<String> findDefaultColumnType(String dbInfoId) throws Exception {
	DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
	Connection conn = null;
	ResultSet resultSet = null;
	try {
		conn = DataSourceUtils.getConnection(ds);
		DatabaseMetaData metaData = conn.getMetaData();
		resultSet = metaData.getTypeInfo();
		List<String> list = new ArrayList<String>();
		while (resultSet.next()) {
			String typeName = resultSet.getString("TYPE_NAME").toUpperCase();
			list.add(typeName);
		}
		return list;
	} finally {
		JdbcUtils.closeResultSet(resultSet);
		JdbcUtils.closeConnection(conn);
	}
}
 
Example 3
Project: bdf2   File: EntityPR.java   View Source Code Vote up 6 votes
private List<String> loadTablePrimaryKeys(String tableName)throws Exception{
	DataSource ds=this.getJdbcTemplate().getDataSource();
	Connection con = DataSourceUtils.getConnection(ds);
	List<String> primaryKeyList=new ArrayList<String>();
	Statement stmt = null;
	ResultSet rs=null;
	try{
		DatabaseMetaData metaData = con.getMetaData();
		rs = metaData.getPrimaryKeys(null, null, tableName.toUpperCase());
		while (rs.next()) {
			primaryKeyList.add(rs.getString("COLUMN_NAME"));
		}
	}finally{
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		JdbcUtils.closeConnection(con);
	}
	return primaryKeyList;
}
 
Example 4
Project: lams   File: AbstractSequenceMaxValueIncrementer.java   View Source Code Vote up 6 votes
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 5
Project: hsweb-framework   File: DynamicSpringManagedTransaction.java   View Source Code Vote up 6 votes
@Override
public Connection getConnection() throws SQLException {
    TransactionProxy proxy = getProxy();
    if (proxy != null) {
        return proxy.getConnection();
    }
    //根据当前激活的数据源 获取jdbc链接
    DataSource dataSource = DataSourceHolder.currentDataSource().getNative();
    String dsId = switcher().currentDataSourceId();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    proxy = new TransactionProxy(dsId, connection, dataSource);
    addProxy(proxy);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "DataSource (" + (dsId == null ? "default" : dsId) + ") JDBC Connection ["
                        + connection
                        + "] will"
                        + (proxy.isConnectionTransactional ? " " : " not ")
                        + "be managed by Spring");
    }

    return connection;
}
 
Example 6
Project: spring4-understanding   File: DatabasePopulatorUtils.java   View Source Code Vote up 6 votes
/**
 * Execute the given {@link DatabasePopulator} against the given {@link DataSource}.
 * @param populator the {@code DatabasePopulator} to execute
 * @param dataSource the {@code DataSource} to execute against
 * @throws DataAccessException if an error occurs, specifically a {@link ScriptException}
 */
public static void execute(DatabasePopulator populator, DataSource dataSource) throws DataAccessException {
	Assert.notNull(populator, "DatabasePopulator must be provided");
	Assert.notNull(dataSource, "DataSource must be provided");
	try {
		Connection connection = DataSourceUtils.getConnection(dataSource);
		try {
			populator.populate(connection);
		}
		finally {
			if (connection != null) {
				DataSourceUtils.releaseConnection(connection, dataSource);
			}
		}
	}
	catch (Exception ex) {
		if (ex instanceof ScriptException) {
			throw (ScriptException) ex;
		}

		throw new UncategorizedScriptException("Failed to execute database script", ex);
	}
}
 
Example 7
Project: spring4-understanding   File: AbstractSequenceMaxValueIncrementer.java   View Source Code Vote up 6 votes
/**
 * Executes the SQL as specified by {@link #getSequenceQuery()}.
 */
@Override
protected long getNextKey() throws DataAccessException {
	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	ResultSet rs = null;
	try {
		stmt = con.createStatement();
		DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
		rs = stmt.executeQuery(getSequenceQuery());
		if (rs.next()) {
			return rs.getLong(1);
		}
		else {
			throw new DataAccessResourceFailureException("Sequence query did not return a result");
		}
	}
	catch (SQLException ex) {
		throw new DataAccessResourceFailureException("Could not obtain sequence value", ex);
	}
	finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 8
Project: blog-java2   File: SpringTestBase.java   View Source Code Vote up 6 votes
protected void executeSql(String path) {
    logger.info("executeSql : " + path);

    Resource resource = new ClassPathResource(path, getClass());
    ResourceDatabasePopulator rdp = new ResourceDatabasePopulator();
    rdp.addScript(resource);
    rdp.setSqlScriptEncoding("UTF-8");
    rdp.setIgnoreFailedDrops(true);
    rdp.setContinueOnError(false);

    try (Connection conn = DataSourceUtils.getConnection(dataSource)) {
        rdp.populate(conn);
    }
    catch (Exception e) {
        throw new IllegalStateException("executeSql failed, path=" + path, e);
    }
}
 
Example 9
Project: ignite   File: CacheSpringStoreSessionListenerSelfTest.java   View Source Code Vote up 6 votes
/**
 */
private void checkConnection() {
    Connection conn = DataSourceUtils.getConnection(jdbc.getDataSource());

    assertNotNull(conn);

    try {
        assertFalse(conn.isClosed());
        assertEquals(!ses.isWithinTransaction(), conn.getAutoCommit());
    }
    catch (SQLException e) {
        throw new RuntimeException(e);
    }

    verifySameInstance(conn);
}
 
Example 10
Project: kansalaisaloite   File: JdbcConfiguration.java   View Source Code Vote up 6 votes
@Bean
public PostgresQueryFactory queryFactory() {
    final DataSource dataSource = dataSource();
    return new PostgresQueryFactory(querydslConfiguration(), new Provider<Connection>() {

        @Override
        public Connection get() {
          Connection conn = DataSourceUtils.getConnection(dataSource);
          if (!DataSourceUtils.isConnectionTransactional(conn, dataSource)) {
              throw new RuntimeException("Connection is not transactional");
          }
          return conn;
        }
        
    });
}
 
Example 11
Project: class-guard   File: DatabasePopulatorUtils.java   View Source Code Vote up 6 votes
/**
 * Execute the given DatabasePopulator against the given DataSource.
 * @param populator the DatabasePopulator to execute
 * @param dataSource the DataSource to execute against
 */
public static void execute(DatabasePopulator populator, DataSource dataSource) {
	Assert.notNull(populator, "DatabasePopulator must be provided");
	Assert.notNull(dataSource, "DataSource must be provided");
	try {
		Connection connection = DataSourceUtils.getConnection(dataSource);
		try {
			populator.populate(connection);
		}
		finally {
			if (connection != null) {
				DataSourceUtils.releaseConnection(connection, dataSource);
			}
		}
	}
	catch (Exception ex) {
		throw new DataAccessResourceFailureException("Failed to execute database script", ex);
	}
}
 
Example 12
Project: oblatum   File: SqlGenerator.java   View Source Code Vote up 6 votes
public List<Column> getColumns(String tableName) throws SQLException {
    List<Column> columns = new ArrayList<Column>();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    DatabaseMetaData metaData = connection.getMetaData();
    ResultSet columnsResultSet = metaData.getColumns(null, metaData.getUserName(), tableName, "%");
    while (columnsResultSet.next()) {
        Column column = new Column();
        column.setColumnName(columnsResultSet.getString("COLUMN_NAME").toLowerCase());
        column.setDataType(columnsResultSet.getInt("DATA_TYPE"));
        column.setTypeName(columnsResultSet.getString("TYPE_NAME"));
        column.setColumnSize(columnsResultSet.getInt("COLUMN_SIZE"));
        column.setNullable(columnsResultSet.getInt("NULLABLE"));
        column.setRemarks(columnsResultSet.getString("REMARKS"));
        column.setColumnDef(columnsResultSet.getString("COLUMN_DEF"));
        column.setOrdinalPosition(columnsResultSet.getInt("ORDINAL_POSITION"));
        column.setIsNullable(columnsResultSet.getString("IS_NULLABLE"));
        column.setIsAutoincrement(columnsResultSet.getString("IS_AUTOINCREMENT"));
        columns.add(column);
    }
    DataSourceUtils.releaseConnection(connection, dataSource);
    return columns;
}
 
Example 13
Project: syncope   File: ProvisioningImpl.java   View Source Code Vote up 6 votes
@Override
public String delete(final String accountid) throws ProvisioningException {
    LOG.debug("Delete request received");

    Connection conn = null;
    try {
        conn = DataSourceUtils.getConnection(dataSource);

        try (PreparedStatement statement = conn.prepareStatement("DELETE FROM user WHERE userId=?")) {
            statement.setString(1, accountid);

            String query = "DELETE FROM user WHERE userId='" + accountid + "';";
            LOG.debug("Execute query: " + query);

            statement.executeUpdate();
        }

        return accountid;
    } catch (SQLException e) {
        throw new ProvisioningException("Delete operation failed", e);
    } finally {
        DataSourceUtils.releaseConnection(conn, dataSource);
    }
}
 
Example 14
Project: SpringClips   File: PersistenceConfigurarion.java   View Source Code Vote up 6 votes
@Bean
@Lazy(false)
public ResourceDatabasePopulator populateDatabase() throws SQLException {
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(new ClassPathResource("data.sql"));

    Connection connection = null;

    try {
        connection = DataSourceUtils.getConnection(dataSource());
        populator.populate(connection);
    } finally {
        if (connection != null) {
            DataSourceUtils.releaseConnection(connection, dataSource());
        }
    }

    return populator;
}
 
Example 15
Project: CommonDao   File: JdbcTxCommonDao.java   View Source Code Vote up 6 votes
/**
 * 添加支持jdbc datasource Transaction 支持的QueryRunner处理方式
 */
@Override
protected QueryRunner getQueryRunner() {
	
	return new QueryRunner(dataSource){

		/* (non-Javadoc)
		 * @see org.apache.commons.dbutils.AbstractQueryRunner#prepareConnection()
		 */
		@Override
		protected Connection prepareConnection() throws SQLException {
			return DataSourceUtils.getConnection(this.getDataSource());
		}

		/* (non-Javadoc)
		 * @see org.apache.commons.dbutils.AbstractQueryRunner#close(java.sql.Connection)
		 */
		@Override
		protected void close(Connection conn) throws SQLException {
			DataSourceUtils.releaseConnection(conn, getDataSource());
		}
		
	};
}
 
Example 16
Project: replyit-master-3.2-final   File: RateCardBL.java   View Source Code Vote up 6 votes
/**
 * Returns a list of column names read from the rate table in the database.
 * @return column names
 */
public List<String> getRateTableColumnNames() {
    DataSource dataSource = jdbcTemplate.getDataSource();
    Connection connection = DataSourceUtils.getConnection(dataSource);

    List<String> columns = Collections.emptyList();

    try {
        columns = JDBCUtils.getAllColumnNames(connection, rateCard.getTableName());
    } catch (SQLException e) {
        throw new SessionInternalError("Could not read columns from rate card table.", e,
                                       new String[] { "RateCardWS,rates,rate.card.cannot.read.rating.table" });

    } finally {
        DataSourceUtils.releaseConnection(connection, dataSource);
    }

    return columns;
}
 
Example 17
Project: replyit-master-3.2-final   File: HSQLDBCacheTest.java   View Source Code Vote up 6 votes
public void testLoader() throws Exception {
    assertEquals("rules_table", loader.getTableName());

    // count the number of records loaded
    DataSource dataSource = getDataSource();
    Connection connection = DataSourceUtils.getConnection(dataSource);

    Statement statement = connection.createStatement();
    ResultSet result = statement.executeQuery("select count(*) as REC_COUNT from " + loader.getTableName());
    result.next();

    long recordsCount = result.getLong("REC_COUNT");
   
    assertTrue("Loader successfully populated records in the database",recordsCount > 0);
    assertEquals("Loaded correct number of records", 1769, recordsCount);

    // cleanup
    result.close();
    statement.close();
    DataSourceUtils.releaseConnection(connection, dataSource);
}
 
Example 18
Project: jkami   File: RunConfing.java   View Source Code Vote up 5 votes
public Connection getConnection() {
    if (dataSource == null) {
        throw new RuntimeException("dataSource is null  no bean dataSource please set spring xml ");
    }
    try {
        return DataSourceUtils.getConnection(dataSource);
    } catch (CannotGetJdbcConnectionException e) {
        try {
            return dataSource.getConnection();
        } catch (SQLException e1) {
            throw new JkException(e);
        }
    }
}
 
Example 19
Project: mylion-mvn   File: SpringJdbc.java   View Source Code Vote up 5 votes
/**
 * 
 * */
public Map<String, Map<String, Object>> query(String sql, String key) {
	try {
		Map<String, Map<String, Object>> resultMap = new KeyMap<Map<String, Object>>();
		Connection conn = DataSourceUtils.getConnection(dataSource);
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			while (rs.next()) {
				Map<String, Object> itemMap = new KeyMap<Object>();
				for (int x = 0; x < rsmd.getColumnCount(); x++) {
					itemMap.put(rsmd.getColumnLabel(x + 1), rs.getObject(x + 1));
				}
				resultMap.put(StringTools.toString(itemMap.get(key)), itemMap);
			}
		} catch (Exception e) {
			MyDogLog.getLog().error(" query ", e);
		} finally {
			JdbcUtils.closeResultSet(rs);
			JdbcUtils.closeStatement(ps);
			DataSourceUtils.releaseConnection(conn, dataSource);
		}

		return resultMap;
	} finally {
		DataSourceUtils.releaseConnection(DataSourceUtils.getConnection(dataSource), dataSource);
	}
}
 
Example 20
Project: lams   File: JdbcTemplate.java   View Source Code Vote up 5 votes
@Override
public <T> T execute(ConnectionCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	try {
		Connection conToUse = con;
		if (this.nativeJdbcExtractor != null) {
			// Extract native JDBC Connection, castable to OracleConnection or the like.
			conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
		}
		else {
			// Create close-suppressing Connection proxy, also preparing returned Statements.
			conToUse = createConnectionProxy(con);
		}
		return action.doInConnection(conToUse);
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("ConnectionCallback", getSql(action), ex);
	}
	finally {
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 21
Project: lams   File: JdbcTemplate.java   View Source Code Vote up 5 votes
@Override
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	try {
		Connection conToUse = con;
		if (this.nativeJdbcExtractor != null &&
				this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) {
			conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
		}
		stmt = conToUse.createStatement();
		applyStatementSettings(stmt);
		Statement stmtToUse = stmt;
		if (this.nativeJdbcExtractor != null) {
			stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
		}
		T result = action.doInStatement(stmtToUse);
		handleWarnings(stmt);
		return result;
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 22
Project: bdf2   File: DbCommonServiceImpl.java   View Source Code Vote up 5 votes
public List<TableInfo> findTableInfos(String dbInfoId) throws Exception {
	List<TableInfo> tablesList = new ArrayList<TableInfo>();
	DataSource ds = this.getDataSourceByDbInfoId(dbInfoId);
	Connection conn = null;
	ResultSet rs = null;
	try {
		conn = DataSourceUtils.getConnection(ds);
		DatabaseMetaData metaData = conn.getMetaData();
		String url = metaData.getURL();
		String schema = null;
		if (url.toLowerCase().contains("oracle")) {
			String value = Configure.getString("bdf2.default.schema");
			if (StringUtils.hasText(value)) {
				schema = value;
			} else {
				schema = metaData.getUserName();
			}
		}
		rs = metaData.getTables(null, schema, "%", new String[] { "TABLE" });
		TableInfo tableInfo = null;
		while (rs.next()) {
			tableInfo = new TableInfo();
			tableInfo.setTableName(rs.getString("TABLE_NAME"));
			tableInfo.setDbInfoId(dbInfoId);
			tablesList.add(tableInfo);
		}
		return tablesList;
	} finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeConnection(conn);
	}
}
 
Example 23
Project: mylion-mvn   File: SpringJdbc.java   View Source Code Vote up 5 votes
/**
 * 
 * */
public Map<String, Map<String, Object>> query(String sql, String key) {
	try {
		Map<String, Map<String, Object>> resultMap = new KeyMap<Map<String, Object>>();
		Connection conn = DataSourceUtils.getConnection(dataSource);
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			while (rs.next()) {
				Map<String, Object> itemMap = new KeyMap<Object>();
				for (int x = 0; x < rsmd.getColumnCount(); x++) {
					itemMap.put(rsmd.getColumnLabel(x + 1), rs.getObject(x + 1));
				}
				resultMap.put(StringTools.toString(itemMap.get(key)), itemMap);
			}
		} catch (Exception e) {
			MyDogLog.getLog().error(" query ", e);
		} finally {
			JdbcUtils.closeResultSet(rs);
			JdbcUtils.closeStatement(ps);
			DataSourceUtils.releaseConnection(conn, dataSource);
		}

		return resultMap;
	} finally {
		DataSourceUtils.releaseConnection(DataSourceUtils.getConnection(dataSource), dataSource);
	}
}
 
Example 24
Project: hsweb-framework   File: DefaultJdbcExecutor.java   View Source Code Vote up 5 votes
@Override
public Connection getConnection() {
    DataSource dataSource = DataSourceHolder.currentDataSource().getNative();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    boolean isConnectionTransactional = DataSourceUtils.isConnectionTransactional(connection, dataSource);
    if (logger.isDebugEnabled()) {
        logger.debug("DataSource ({}) JDBC Connection [{}] will {}be managed by Spring", getDatasourceId(), connection, (isConnectionTransactional ? "" : "not "));
    }
    return connection;
}
 
Example 25
Project: spring4-understanding   File: AbstractIdentityColumnMaxValueIncrementer.java   View Source Code Vote up 5 votes
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that @@identity
		* returns the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate(getIncrementStatement());
				ResultSet rs = stmt.executeQuery(getIdentityStatement());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("Identity statement failed after inserting");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			stmt.executeUpdate(getDeleteStatement(this.valueCache));
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 26
Project: spring4-understanding   File: JdbcTemplate.java   View Source Code Vote up 5 votes
@Override
public <T> T execute(ConnectionCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	try {
		Connection conToUse = con;
		if (this.nativeJdbcExtractor != null) {
			// Extract native JDBC Connection, castable to OracleConnection or the like.
			conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
		}
		else {
			// Create close-suppressing Connection proxy, also preparing returned Statements.
			conToUse = createConnectionProxy(con);
		}
		return action.doInConnection(conToUse);
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("ConnectionCallback", getSql(action), ex);
	}
	finally {
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 27
Project: spring4-understanding   File: JdbcTemplate.java   View Source Code Vote up 5 votes
@Override
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	try {
		Connection conToUse = con;
		if (this.nativeJdbcExtractor != null &&
				this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) {
			conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
		}
		stmt = conToUse.createStatement();
		applyStatementSettings(stmt);
		Statement stmtToUse = stmt;
		if (this.nativeJdbcExtractor != null) {
			stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
		}
		T result = action.doInStatement(stmtToUse);
		handleWarnings(stmt);
		return result;
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 28
Project: spring4-understanding   File: AbstractDatabasePopulatorTests.java   View Source Code Vote up 5 votes
/**
 * See SPR-9457
 */
@Test
public void usesBoundConnectionIfAvailable() throws SQLException {
	TransactionSynchronizationManager.initSynchronization();
	Connection connection = DataSourceUtils.getConnection(db);
	DatabasePopulator populator = mock(DatabasePopulator.class);
	DatabasePopulatorUtils.execute(populator, db);
	verify(populator).populate(connection);
}
 
Example 29
Project: petapojo   File: Database.java   View Source Code Vote up 5 votes
/**
 * 打开数据库连接
 */
private void openConnection() {
    try {
        if (sharedCOnnectionDepth == 0) {
            sharedConnection = DataSourceUtils.getConnection(dataSource);
            sharedCOnnectionDepth++;
        }
    } catch (Exception ex) {
        throw new PetaPojoException("open connection error", ex);
    }
}
 
Example 30
Project: unitils   File: DataSourceWrapper.java   View Source Code Vote up 5 votes
/**
 * 
 * @return A connection from the data source, not null
 */
public Connection getConnection() {
    try {
        connection = DataSourceUtils.getConnection(wrappedDataSource);
        
        return DatabaseUnitils.getGoodConnection(connection, wrappedDataSource);
    } catch (Exception e) {
        throw new UnitilsException("Unable to connect to database for " + databaseConfiguration + ".", e);
    }
}
 
Example 31
Project: unitils   File: DbUnitDatabaseConnection.java   View Source Code Vote up 5 votes
/**
 * Returns a <code>Connection</code> that can be used by DBUnit. A reference to the connection is kept, to be able
 * to 'close' it (return it to the connection pool) after the DBUnit operation finished. If an open connection
 * is already in use by DBUnit, this connection is returned
 *
 * @return A JDBC connection
 */
public Connection getConnection() throws SQLException {
    if (currentlyUsedConnection == null) {
        currentlyUsedConnection = DataSourceUtils.getConnection(dataSource);
        currentlyUsedNativeConnection = getNativeConnection(currentlyUsedConnection);
    }
    
    
    /*if (dataSource instanceof BasicDataSource) {
        BasicDataSource tempDataSource = (BasicDataSource) dataSource;
        boolean canAccess = tempDataSource.isAccessToUnderlyingConnectionAllowed();
        if (!canAccess) {
            tempDataSource.setAccessToUnderlyingConnectionAllowed(true);
        }
        if (tempDataSource.getDriverClassName().toLowerCase().contains("oracle")  && currentlyUsedNativeConnection instanceof DelegatingConnection) {
            DelegatingConnection tempConnection = (DelegatingConnection) currentlyUsedNativeConnection;
            return tempConnection.getInnermostDelegate();
        }
        if (!canAccess) {
            tempDataSource.setAccessToUnderlyingConnectionAllowed(false);
        } 
        
    }
    return currentlyUsedNativeConnection;*/
    
    return DatabaseUnitils.getGoodConnection(currentlyUsedNativeConnection, dataSource);
}
 
Example 32
Project: jdbc   File: PostgresTestSupport.java   View Source Code Vote up 5 votes
@Override
protected void obtainResource() {
	context = new SpringApplicationBuilder(Config.class)
			.web(WebApplicationType.NONE)
			.run();
	DataSource dataSource = context.getBean(DataSource.class);
	Connection con = DataSourceUtils.getConnection(dataSource);
	DataSourceUtils.releaseConnection(con, dataSource);
}
 
Example 33
Project: cqrs-hotel   File: JdbcConfiguration.java   View Source Code Vote up 5 votes
@PostConstruct
public void statusReport() throws SQLException {
    try (Connection connection = DataSourceUtils.getConnection(dataSource)) {
        DatabaseMetaData metaData = connection.getMetaData();
        log.info("Database: {} {}", metaData.getDatabaseProductName(), metaData.getDatabaseProductVersion());
        log.info("User: {}", metaData.getUserName());
        log.info("Connection URL: {} (configuration was {})", metaData.getURL(), dataSourceProperties.getUrl());
        log.info("Flyway locations: {}", flywayProperties.getLocations());
    }
}
 
Example 34
Project: bamboobsc   File: DataUtils.java   View Source Code Vote up 5 votes
public static Connection getConnection(DataSource dataSource) 
	throws CannotGetJdbcConnectionException, Exception {
	
	if (dataSource==null) {
		return null;
	}
	return DataSourceUtils.getConnection(dataSource);
}
 
Example 35
Project: mybatis-spring-1.2.2   File: SpringManagedTransaction.java   View Source Code Vote up 5 votes
/**
 * Gets a connection from Spring transaction manager and discovers if this
 * {@code Transaction} should manage connection or let it to Spring.
 * <p>
 * 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");
  }
}
 
Example 36
Project: cernunnos   File: OpenConnectionTask.java   View Source Code Vote up 5 votes
protected void performCreateConnection(TaskRequest req, TaskResponse res, DataSource dataSource) {
    final Connection connection = DataSourceUtils.getConnection(dataSource);
 try {
	    // Make it available as a request attribute...
        final String connectionAttrName = (String) attribute_name.evaluate(req, res);
        res.setAttribute(connectionAttrName, connection);
        
        // Invoke subtasks...
        super.performSubtasks(req, res);
 }
 finally {
     DataSourceUtils.releaseConnection(connection, dataSource);
 }
}
 
Example 37
Project: fiware-rss   File: DatabaseLoader.java   View Source Code Vote up 5 votes
/**
 * Method to insert data before test. throws Exception from DB.
 * 
 * @throws Exception
 *             the exception
 */
public void init() throws Exception {
    DatabaseLoader.logger.debug("DatabaseLoader.init()");

    try {
        DatabaseLoader.logger.debug("starting init() in DatabaseLoader...");

        this.dbConn = new DatabaseConnection(DataSourceUtils.getConnection(dataSource), this.schema);

        DatabaseConfig config = dbConn.getConfig();
        config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
        config.setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, new MySqlMetadataHandler());
        config.setProperty(DatabaseConfig.FEATURE_CASE_SENSITIVE_TABLE_NAMES, Boolean.TRUE);
        DatabaseLoader.logger.debug("DATASOURCE." + dataSource.toString());
        this.loader = new FlatXmlDataSetBuilder();

        dbConn.getConnection().createStatement().execute("DELETE FROM dbe_transaction");
        deleteAll("dbunit/CREATE_DATATEST_III.xml", false);
        deleteAll("dbunit/CREATE_DATATEST_II.xml", false);
        deleteAll("dbunit/CREATE_DATATEST_I.xml", false);

        cleanInsert("dbunit/CREATE_DATATEST_I.xml", false);
        cleanInsert("dbunit/CREATE_DATATEST_II.xml", false);
        cleanInsert("dbunit/CREATE_DATATEST_III.xml", true);

        DatabaseLoader.logger.debug("ending init() in DatabaseLoader...");

    } catch (Exception e) {
        DatabaseLoader.logger.error("Error loading data init in DatabaseLoader");
        dbConn.getConnection().rollback();
        e.printStackTrace();
        throw e;
    }
}
 
Example 38
Project: InSpider   File: GeneralizeReader.java   View Source Code Vote up 5 votes
@Transactional(propagation=Propagation.MANDATORY)
public void delete() throws SQLException, IOException {
	Connection connection = DataSourceUtils.getConnection(dataSource);
	
	Statement stmt = connection.createStatement();
	for(GeneralizeJob job : generalizerConfig.getGeneralizeJobs()) {
		String destination = job.getDestination();
		
		logger.debug("" + stmt.executeUpdate("delete from " + destination) + 
			" features deleted from " + destination);
	}
	stmt.close();
	
	DataSourceUtils.releaseConnection(connection, dataSource);
}
 
Example 39
Project: oblatum   File: SqlGenerator.java   View Source Code Vote up 5 votes
public List<String> getPrimaryKeys(String tableName) throws SQLException {
    List<String> primaryKeys = new ArrayList<String>();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    DatabaseMetaData metaData = connection.getMetaData();
    ResultSet primaryKeysResultSet = metaData.getPrimaryKeys(null, metaData.getUserName(), tableName);
    while (primaryKeysResultSet.next()) {
        primaryKeys.add(primaryKeysResultSet.getString("COLUMN_NAME").toLowerCase());
    }
    DataSourceUtils.releaseConnection(connection, dataSource);
    return primaryKeys;
}
 
Example 40
Project: class-guard   File: JdbcTemplate.java   View Source Code Vote up 5 votes
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	try {
		Connection conToUse = con;
		if (this.nativeJdbcExtractor != null &&
				this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativeStatements()) {
			conToUse = this.nativeJdbcExtractor.getNativeConnection(con);
		}
		stmt = conToUse.createStatement();
		applyStatementSettings(stmt);
		Statement stmtToUse = stmt;
		if (this.nativeJdbcExtractor != null) {
			stmtToUse = this.nativeJdbcExtractor.getNativeStatement(stmt);
		}
		T result = action.doInStatement(stmtToUse);
		handleWarnings(stmt);
		return result;
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 41
Project: class-guard   File: DatabasePopulatorTests.java   View Source Code Vote up 5 votes
/**
 * See SPR-9457
 */
@Test
public void usesBoundConnectionIfAvailable() throws SQLException {
	TransactionSynchronizationManager.initSynchronization();
	Connection connection = DataSourceUtils.getConnection(db);
	DatabasePopulator populator = mock(DatabasePopulator.class);
	DatabasePopulatorUtils.execute(populator, db);
	verify(populator).populate(connection);
}
 
Example 42
Project: fiware-rss   File: ProcessingLimitServiceTest.java   View Source Code Vote up 5 votes
/**
 * @throws Exception
 */
@After
public void tearDown() throws Exception {
    FlatXmlDataSetBuilder loader = new FlatXmlDataSetBuilder();
    IDatabaseConnection dbConn = new DatabaseConnection(DataSourceUtils.getConnection(dataSource), this.schema);
    URL url = this.getClass().getClassLoader().getResource("dbunit/CREATE_DATATEST_EXPLIMIT.xml");
    IDataSet ds = loader.build(url);
    DatabaseOperation.DELETE_ALL.execute(dbConn, ds);
    dbConn.getConnection().commit();
}
 
Example 43
Project: plow   File: StatsDaoImpl.java   View Source Code Vote up 5 votes
@Override
public void batchUpdateProcRuntimeStats(List<RunningTask> tasks) {

    Collections.sort(tasks, SORT_BY_PROC);

    final Connection conn = DataSourceUtils.getConnection(jdbc.getDataSource());
    final BatchSqlUpdate batch = new BatchSqlUpdate(
            jdbc.getDataSource(), UPDATE_PROC, PROC_BATCH_TYPES);

    for (RunningTask task: tasks) {
        final float cores = task.cpuPercent / 100.0f;
        final Long[] io_stats = new Long[] { 0L, 0L, 0L, 0L };
        if (task.diskIO != null) {
            io_stats[0] = task.diskIO.readCount;
            io_stats[1] = task.diskIO.writeCount;
            io_stats[2] =  task.diskIO.readBytes;
            io_stats[3] =  task.diskIO.writeBytes;;
        }

        try {
            batch.update(
                    task.rssMb,
                    task.rssMb,
                    (int) Math.min(100, Math.round(task.progress)),
                    cores,
                    cores,
                    task.lastLog,
                    conn.createArrayOf("bigint", io_stats),
                    UUID.fromString(task.procId),
                    UUID.fromString(task.taskId));
        } catch (SQLException e) {
            // Will fail of createArrayOf fails
            logger.warn(
                    "Failed to update proc {} with task {} due to array formating, {}",
                    new Object[] { task.procId, task.taskId, e });
        }
    }

    batch.flush();
}
 
Example 44
Project: qb-core   File: RmJdbcTemplate.java   View Source Code Vote up 5 votes
public Object execute(StatementCallback action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	try {
		Connection conToUse = con;
		if (getNativeJdbcExtractor() != null &&
				getNativeJdbcExtractor().isNativeConnectionNecessaryForNativeStatements()) {
			conToUse = getNativeJdbcExtractor().getNativeConnection(con);
		}
		stmt = conToUse.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
		applyStatementSettings(stmt);
		Statement stmtToUse = stmt;
		if (getNativeJdbcExtractor() != null) {
			stmtToUse = getNativeJdbcExtractor().getNativeStatement(stmt);
		}
		Object result = action.doInStatement(stmtToUse);
		handleWarnings(stmt);
		return result;
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 45
Project: MybatisSpring2.5.X   File: SpringManagedTransaction.java   View Source Code Vote up 5 votes
/**
 * Gets a connection from Spring transaction manager and discovers if this
 * {@code Transaction} should manage connection or let it to Spring.
 * <p>
 * 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 = isConnectionTransactional(this.connection, this.dataSource);

  if (logger.isDebugEnabled()) {
    logger.debug(
        "JDBC Connection ["
            + this.connection
            + "] will"
            + (this.isConnectionTransactional ? " " : " not ")
            + "be managed by Spring");
  }
}
 
Example 46
Project: fixflow   File: DBConnFactory.java   View Source Code Vote up 5 votes
public DBConnection createDBConnection() throws SQLException{
	DBConnection dbconn = new DBConnection();
	Connection connection = DataSourceUtils.getConnection(dataSource);
	dbconn.setConnection(connection);
	dbconn.setDataSource(dataSource);
	return dbconn;
}
 
Example 47
Project: edct-formbuilder   File: DataSetTestExecutionListener.java   View Source Code Vote up 5 votes
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;

  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);
}
 
Example 48
Project: replyit-master-3.2-final   File: RateCardBL.java   View Source Code Vote up 5 votes
private void checkRateTableExistance(String tableName) throws SQLException {
   	
       DataSource dataSource = jdbcTemplate.getDataSource();
       Connection connection = DataSourceUtils.getConnection(dataSource);
   	List<String> tableNames = JDBCUtils.getAllTableNames(connection);
   	if (tableNames.contains(tableName.toLowerCase())) {
   		throw new SessionInternalError("Exception saving rates to database.", 
   				new String[] { "RateCardWS,rates,rate.card.db.exist," + tableName});
   	}
}
 
Example 49
Project: copper-engine   File: SpringTransaction.java   View Source Code Vote up 5 votes
public void run(PlatformTransactionManager transactionManager, DataSource dataSource, TransactionDefinition def) throws Exception {
    TransactionStatus txnStatus = transactionManager.getTransaction(def);
    try {
        Connection con = DataSourceUtils.getConnection(dataSource);
        try {
            execute(con);
        } finally {
            DataSourceUtils.releaseConnection(con, dataSource);
        }
    } catch (Exception e) {
        transactionManager.rollback(txnStatus);
        throw e;
    }
    transactionManager.commit(txnStatus);
}
 
Example 50
Project: javasec   File: RmJdbcTemplate.java   View Source Code Vote up 5 votes
public Object execute(StatementCallback action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	try {
		Connection conToUse = con;
		if (getNativeJdbcExtractor() != null &&
				getNativeJdbcExtractor().isNativeConnectionNecessaryForNativeStatements()) {
			conToUse = getNativeJdbcExtractor().getNativeConnection(con);
		}
		stmt = conToUse.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
		applyStatementSettings(stmt);
		Statement stmtToUse = stmt;
		if (getNativeJdbcExtractor() != null) {
			stmtToUse = getNativeJdbcExtractor().getNativeStatement(stmt);
		}
		Object result = action.doInStatement(stmtToUse);
		handleWarnings(stmt);
		return result;
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 51
Project: java-lib   File: RmJdbcTemplate.java   View Source Code Vote up 5 votes
public Object execute(StatementCallback action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(getDataSource());
	Statement stmt = null;
	try {
		Connection conToUse = con;
		if (getNativeJdbcExtractor() != null &&
				getNativeJdbcExtractor().isNativeConnectionNecessaryForNativeStatements()) {
			conToUse = getNativeJdbcExtractor().getNativeConnection(con);
		}
		stmt = conToUse.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
		applyStatementSettings(stmt);
		Statement stmtToUse = stmt;
		if (getNativeJdbcExtractor() != null) {
			stmtToUse = getNativeJdbcExtractor().getNativeStatement(stmt);
		}
		Object result = action.doInStatement(stmtToUse);
		handleWarnings(stmt);
		return result;
	}
	catch (SQLException ex) {
		// Release Connection early, to avoid potential connection pool deadlock
		// in the case when the exception translator hasn't been initialized yet.
		JdbcUtils.closeStatement(stmt);
		stmt = null;
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw getExceptionTranslator().translate("StatementCallback", getSql(action), ex);
	}
	finally {
		JdbcUtils.closeStatement(stmt);
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example 52
Project: spark-project   File: SpringConfig.java   View Source Code Vote up 4 votes
@Override
public Connection getConnection() throws SQLException {
    return DataSourceUtils.getConnection(dataSource);
}
 
Example 53
Project: spwrap   File: ConnectionManager.java   View Source Code Vote up 4 votes
Connection getConnection(DataSource dataSource) {
    return DataSourceUtils.getConnection(dataSource);
}
 
Example 54
Project: bdf2   File: EntityPR.java   View Source Code Vote up 4 votes
@SuppressWarnings("unchecked")
@Expose
public Collection<ColumnDef> buildSQLFields(Map<String,Object> map) throws Exception{
	String querySql=(String)map.get("querySql");
	querySql=parseQuerySql(querySql,map);
	final String tableName=(String)map.get("tableName");
	Collection<Map<String,Object>> parameters=(Collection<Map<String,Object>>)map.get("parameters");
	MapSqlParameterSource sqlParameters=new MapSqlParameterSource();
	if(parameters!=null){
		for(Map<String,Object> pmap:parameters){
			sqlParameters.addValue((String)pmap.get("name"), pmap.get("value"));
		}
	}
	final List<String> primaryKeyList=this.loadTablePrimaryKeys(tableName);
	
	DataSource ds=this.getJdbcTemplate().getDataSource();
	Connection con = DataSourceUtils.getConnection(ds);
	Collection<ColumnDef> columns=null;
	try{
		final DatabaseMetaData databaseMetaData=con.getMetaData();
		columns=this.getNamedParameterJdbcTemplate().query(querySql, sqlParameters, new ResultSetExtractor<Collection<ColumnDef>>(){
			public Collection<ColumnDef> extractData(ResultSet rs) throws SQLException,DataAccessException {
				Collection<ColumnDef> result=new ArrayList<ColumnDef>();
				ResultSetMetaData rsmd = rs.getMetaData();
				int count = rsmd.getColumnCount();
				for (int i = 1; i <= count; i++) {
					ColumnDef col=new ColumnDef();
					col.setTableName(rsmd.getTableName(i));
					col.setName(rsmd.getColumnName(i));
					int columnType=rsmd.getColumnType(i);
					String type="String";
					if(columnType==Types.INTEGER || columnType ==Types.BIGINT || columnType==Types.SMALLINT || columnType==Types.TINYINT){
						type="int";
					}else if(columnType==Types.BOOLEAN){
						type="Boolean";
					}else if(columnType==Types.DATE){
						type="Date";
					}else if(columnType==Types.TIMESTAMP){
						type="DateTime";
					}else if(columnType==Types.TIME){
						type="Time";
					}else if(columnType==Types.DECIMAL || columnType==Types.NUMERIC){
						type="BigDecimal";
					}else if(columnType==Types.FLOAT){
						type="Float";
					}else if(columnType==Types.DOUBLE){
						type="double";
					}
					col.setLabel(getColumnRemarks(col.getTableName(),col.getName(),databaseMetaData));
					setPrimaryKey(col,tableName,primaryKeyList);
					col.setType(type);
					result.add(col);
				}
				return result;
			}
		});
		
	}finally{
		JdbcUtils.closeConnection(con);	
	}
	return columns;
}
 
Example 55
Project: lams   File: SqlServerMaxValueIncrementer.java   View Source Code Vote up 4 votes
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that @@identity
		* returnes the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate("insert into " + getIncrementerName() + " default values");
				ResultSet rs = stmt.executeQuery("select @@identity");
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("@@identity failed after executing an update");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			long maxValue = this.valueCache[(this.valueCache.length - 1)];
			stmt.executeUpdate("delete from " + getIncrementerName() + " where " + getColumnName() + " < " + maxValue);
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 56
Project: lams   File: DerbyMaxValueIncrementer.java   View Source Code Vote up 4 votes
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that last_insert_id()
		* returned the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate("insert into " + getIncrementerName() + " (" + getDummyName() + ") values(null)");
				ResultSet rs = stmt.executeQuery("select IDENTITY_VAL_LOCAL() from " + getIncrementerName());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("IDENTITY_VAL_LOCAL() failed after executing an update");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			long maxValue = this.valueCache[(this.valueCache.length - 1)];
			stmt.executeUpdate("delete from " + getIncrementerName() + " where " + getColumnName() + " < " + maxValue);
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not obtain IDENTITY value", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 57
Project: lams   File: HsqlMaxValueIncrementer.java   View Source Code Vote up 4 votes
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same Connection. Otherwise we can't be sure that last_insert_id()
		* returned the correct value.
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate("insert into " + getIncrementerName() + " values(null)");
				ResultSet rs = stmt.executeQuery("select max(identity()) from " + getIncrementerName());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("identity() failed after executing an update");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			long maxValue = this.valueCache[(this.valueCache.length - 1)];
			stmt.executeUpdate("delete from " + getIncrementerName() + " where " + getColumnName() + " < " + maxValue);
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not obtain identity()", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 58
Project: jTransactions   File: SpringTxConnectionManager.java   View Source Code Vote up 4 votes
@Override
public Connection getConnection(DataSource ds) throws SQLException {
	return DataSourceUtils.getConnection(ds);
}
 
Example 59
Project: mylion-mvn   File: SpringJdbc.java   View Source Code Vote up 4 votes
/**
 * 查询表元数据相关信息
 */
public Map<String, ResultType> queryTableMetas(String tableName) {
	Map<String, ResultType> resultTypes = new HashMap<String, ResultType>();
	Map<String, Map<String, Object>> columnInfo = query(String.format(SHOW_TABLE_DESC_SQL, tableName), "field");
	Connection connection = DataSourceUtils.getConnection(dataSource);
	PreparedStatement ps = null;
	ResultSet rs = null;
	XmlConfigLoader configLoader = XmlConfigLoader.getConfigLoader();
	TableModel tableModel = configLoader.getTableMap().get(tableName) ;
	try {
		ps = connection.prepareStatement(String.format("select * from %s", tableName));
		rs = ps.executeQuery();
		ResultSetMetaData rsmd = rs.getMetaData();
		int cloumnLength = rsmd.getColumnCount();
		
		for(int x=0;x<cloumnLength;x++){
			ResultType resultType = new ResultType();
			String field = rsmd.getColumnLabel(x+1);
			Map<String, Object> fieldMap = columnInfo.get( field );
			String extra = StringTools.toString(fieldMap.get("extra")) ;
			resultType.setAutoIncrement("auto_increment".equals(extra)) ; 
			resultType.setPri("pri".equalsIgnoreCase(StringTools.toString(fieldMap.get("key")))) ; 
			resultType.setColumnLabel(field) ;
			resultType.setColumnName( rsmd.getColumnName(x+1) ) ;
			ColumnOverride columnOverride = tableModel.getColumnOverride().get( field ) ;
			
			resultType.setColumnType( rsmd.getColumnType(x+1) ) ;
			if(columnOverride == null){
				resultType.setColumnTypeName( resultType.getJdbcType().name() ) ;
				resultType.setClassName(rsmd.getColumnClassName(x+1)) ;
			}else{
				resultType.setColumnTypeName(columnOverride.getJdbcType().name()) ;
				resultType.setClassName( columnOverride.getJavaType() ) ; 
			}
			
			resultType.setProperty( StringTools.toProperty(field) ) ;
			resultType.setComment( StringTools.toString( fieldMap.get("comment"))) ;
			resultType.setGenerateClassName( resultType.getClassName().replaceAll("java.lang.", "")); 
			
			/*修改链接符号*/
			ColumnSymbol columnSymbol = tableModel.getColumnSymbols().get( field ) ;
			if(null != columnSymbol){
				columnSymbol.setQueryValue( columnSymbol.getValue().replaceAll("\\{value\\}", "#{"+resultType.getProperty()+"}")); 
				resultType.setColumnSymbol( columnSymbol );
			}
			 
			/*设置字段显示的值*/
			resultType.setColumnValue( tableModel.getColumnValue().get(field) ) ;
			resultTypes.put(field, resultType) ; 
			
		}
	} catch (Exception e) {
		MyDogLog.getLog().error(" queryTableMetas ", e);
	} finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(ps);
		DataSourceUtils.releaseConnection(connection, dataSource);
	}

	return resultTypes;
}
 
Example 60
Project: mylion-mvn   File: SpringJdbc.java   View Source Code Vote up 4 votes
/**
 * 查询表元数据相关信息
 */
public Map<String, ResultType> queryTableMetas(String tableName) {
	Map<String, ResultType> resultTypes = new KeyMap<ResultType>(); 
	Map<String, Map<String, Object>> columnInfo = query(String.format(SHOW_TABLE_DESC_SQL, tableName), "field");
	Connection connection = DataSourceUtils.getConnection(dataSource);
	PreparedStatement ps = null;
	ResultSet rs = null;
	XmlConfigLoader configLoader = XmlConfigLoader.getConfigLoader();
	TableModel tableModel = configLoader.getTableMap().get(tableName) ;
	try {
		ps = connection.prepareStatement(String.format("select * from %s", tableName));
		rs = ps.executeQuery();
		ResultSetMetaData rsmd = rs.getMetaData();
		int cloumnLength = rsmd.getColumnCount();
		
		for(int x=0;x<cloumnLength;x++){
			ResultType resultType = new ResultType();
			String field = rsmd.getColumnLabel(x+1);
			Map<String, Object> fieldMap = columnInfo.get( field );
			String extra = StringTools.toString(fieldMap.get("extra")) ;
			resultType.setAutoIncrement("auto_increment".equals(extra)) ; 
			resultType.setPri("pri".equalsIgnoreCase(StringTools.toString(fieldMap.get("key")))) ; 
			resultType.setColumnLabel(field) ;
			resultType.setColumnName( rsmd.getColumnName(x+1) ) ;
			ColumnOverride columnOverride = tableModel.getColumnOverride().get( field ) ;
			
			resultType.setColumnType( rsmd.getColumnType(x+1) ) ;
			if(columnOverride == null){
				resultType.setColumnTypeName( resultType.getJdbcType().name() ) ;
				resultType.setClassName(rsmd.getColumnClassName(x+1)) ;
			}else{
				resultType.setColumnTypeName(columnOverride.getJdbcType().name()) ;
				resultType.setClassName( columnOverride.getJavaType() ) ; 
			}
			
			resultType.setProperty( StringTools.toProperty(field) ) ;
			resultType.setComment( StringTools.toString( fieldMap.get("comment"))) ;
			resultType.setGenerateClassName( resultType.getClassName().replaceAll("java.lang.", "")); 
			
			/*修改链接符号*/
			ColumnSymbol columnSymbol = tableModel.getColumnSymbols().get( field ) ;
			if(null != columnSymbol){
				columnSymbol.setQueryValue( columnSymbol.getValue().replaceAll("\\{value\\}", "#{"+resultType.getProperty()+"}")); 
				resultType.setColumnSymbol( columnSymbol );
			}
			 
			/*设置字段显示的值*/
			resultType.setColumnValue( tableModel.getColumnValue().get(field) ) ;
			
			resultTypes.put(field, resultType) ; 
			
		}
	} catch (Exception e) {
		MyDogLog.getLog().error(" queryTableMetas ", e);
	} finally {
		JdbcUtils.closeResultSet(rs);
		JdbcUtils.closeStatement(ps);
		DataSourceUtils.releaseConnection(connection, dataSource);
	}

	return resultTypes;
}
 
Example 61
Project: lodsve-framework   File: MySQLIDGenerator.java   View Source Code Vote up 4 votes
@Override
 public synchronized Long nextId(String sequenceName) {
     if (NEXT_ID_CACHE.get(sequenceName) != null) {
         this.nextId = NEXT_ID_CACHE.get(sequenceName);
     }
     if (MAX_ID_CACHE.get(sequenceName) != null) {
         this.maxId = MAX_ID_CACHE.get(sequenceName);
     }

     if (this.maxId == this.nextId) {
         /*
         * Need to use straight JDBC code because we need to make sure that the insert and select
* are performed on the same connection (otherwise we can't be sure that last_insert_id()
* returned the correct value)
*/

         Connection con = DataSourceUtils.getConnection(dataSource);
         Statement stmt = null;
         try {
             stmt = con.createStatement();
             DataSourceUtils.applyTransactionTimeout(stmt, dataSource);
             String updateSql = "update " + sequenceName + " set " + sequenceName + " = last_insert_id(" + sequenceName + " + " + getCacheSize() + ")";
             try {
                 // Increment the sequence column...
                 stmt.executeUpdate(updateSql);
             } catch (SQLException e) {
                 //发生异常,即不存在这张表
                 //1.执行新建这张表的语句
                 StringBuffer createSql = new StringBuffer();
                 createSql.append("create table ").append(sequenceName).append(" ( ");
                 createSql.append(sequenceName).append(" bigint(12) default null ");
                 createSql.append(" ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ");
                 stmt.execute(createSql.toString());
                 //2.初始化这张表的数据(将name的值置为0)
                 String initDataSql = "insert into " + sequenceName + " values(0)";
                 stmt.executeUpdate(initDataSql);
                 //3.Increment the sequence column...
                 stmt.executeUpdate(updateSql);
             }
             // Retrieve the new max of the sequence column...
             ResultSet rs = stmt.executeQuery(VALUE_SQL);
             try {
                 if (!rs.next()) {
                     throw new DataAccessResourceFailureException("last_insert_id() failed after executing an update");
                 }
                 this.maxId = rs.getLong(1);
                 //更新缓存
                 MAX_ID_CACHE.put(sequenceName, this.maxId);
             } finally {
                 JdbcUtils.closeResultSet(rs);
             }
             this.nextId = this.maxId - getCacheSize() + 1;
             //更新缓存
             NEXT_ID_CACHE.put(sequenceName, this.nextId);
         } catch (SQLException ex) {
             throw new DataAccessResourceFailureException("Could not obtain last_insert_id()", ex);
         } finally {
             JdbcUtils.closeStatement(stmt);
             DataSourceUtils.releaseConnection(con, dataSource);
         }
     } else {
         this.nextId++;
         //更新缓存
         NEXT_ID_CACHE.put(sequenceName, this.nextId);
     }
     long result = this.nextId;

     //初始化nextId和maxId
     this.nextId = 0;
     this.maxId = 0;
     return result;
 }
 
Example 62
Project: spring4-understanding   File: MySQLMaxValueIncrementer.java   View Source Code Vote up 4 votes
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.maxId == this.nextId) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that last_insert_id()
		* returned the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			// Increment the sequence column...
			String columnName = getColumnName();
			stmt.executeUpdate("update "+ getIncrementerName() + " set " + columnName +
					" = last_insert_id(" + columnName + " + " + getCacheSize() + ")");
			// Retrieve the new max of the sequence column...
			ResultSet rs = stmt.executeQuery(VALUE_SQL);
			try {
				if (!rs.next()) {
					throw new DataAccessResourceFailureException("last_insert_id() failed after executing an update");
				}
				this.maxId = rs.getLong(1);
			}
			finally {
				JdbcUtils.closeResultSet(rs);
			}
			this.nextId = this.maxId - getCacheSize() + 1;
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not obtain last_insert_id()", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	else {
		this.nextId++;
	}
	return this.nextId;
}
 
Example 63
Project: tcc-transaction   File: SpringJdbcTransactionRepository.java   View Source Code Vote up 4 votes
protected Connection getConnection() {
    return DataSourceUtils.getConnection(this.getDataSource());
}
 
Example 64
Project: ryf_mms2   File: DAOSupport.java   View Source Code Vote up 4 votes
/**
 * 得到数据库Connection对象
 * @return Connection
 */
public Connection getConnection() {
	CustomerContextHolder.setMaster();
	return DataSourceUtils.getConnection(dtm.getDataSource());
}
 
Example 65
Project: treeleaf   File: SpringDBConnectionFactory.java   View Source Code Vote up 4 votes
public Connection getConnection() {
    return DataSourceUtils.getConnection(this.dataSource);
}
 
Example 66
Project: spring-jdbctemplate-streams   File: JdbcStream.java   View Source Code Vote up 4 votes
public StreamableQuery streamableQuery(String sql, Object... args) throws SQLException {
    Connection connection = DataSourceUtils.getConnection(getDataSource());
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    newArgPreparedStatementSetter(args).setValues(preparedStatement);
    return new StreamableQuery(connection, preparedStatement);
}
 
Example 67
Project: uranus   File: DBConnectionProviderServiceImpl.java   View Source Code Vote up 4 votes
@Override
public Connection getConnection() throws Exception {
	return DataSourceUtils.getConnection(_ds);
}
 
Example 68
Project: rdb   File: SpringDataSourceManager.java   View Source Code Vote up 4 votes
@Override
public Connection getConnection() {
    return DataSourceUtils.getConnection(dataSource);
}
 
Example 69
Project: sdcct   File: AbstractDbServer.java   View Source Code Vote up 4 votes
protected void executeInitializationScripts() {
    SdcctDriverDataSource adminDataSrc = null;
    Connection adminConn = null;

    try {
        adminConn = DataSourceUtils.getConnection((adminDataSrc = this.dataSrcConfig.buildDataSource(this.adminUser, true)));

        for (ResourceSource initScriptSrc : this.initScriptSrcs) {
            ScriptUtils
                .executeSqlScript(adminConn,
                    new EncodedResource(new ByteArrayResource(this.embeddedPlaceholderResolver
                        .resolvePlaceholders(new String(initScriptSrc.getBytes(), StandardCharsets.UTF_8)).getBytes(StandardCharsets.UTF_8),
                        initScriptSrc.getResource().getDescription()), StandardCharsets.UTF_8));
        }

        DbUser user = this.dataSrcConfig.getUser();
        String userName = user.getName();
        Map<String, DbRole> roles = user.getRoles();
        StrBuilder secSqlBuilder = new StrBuilder();

        secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getCreateUserString(userName, user.getCredentials()));
        secSqlBuilder.appendNewLine();

        for (String roleName : roles.keySet()) {
            secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getCreateRoleString(roleName));
            secSqlBuilder.appendNewLine();
            secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getGrantRoleString(roleName, userName));

            for (DbAuthority authority : roles.get(roleName).getAuthorities()) {
                secSqlBuilder.appendNewLine();
                secSqlBuilder.append(SdcctHsqlDialect.INSTANCE.getGrantOnString(authority, roleName));
            }
        }

        ScriptUtils.executeSqlScript(adminConn,
            new EncodedResource(new ByteArrayResource(secSqlBuilder.build().getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));

        adminConn.commit();
    } catch (Exception e) {
        throw new HibernateException(String.format("Unable to execute database (name=%s) server (hostAddr=%s, port=%d) initialization scripts.",
            this.dbName, this.hostAddr, this.port), e);
    } finally {
        if (adminConn != null) {
            DataSourceUtils.releaseConnection(adminConn, adminDataSrc);
        }
    }
}
 
Example 70
Project: class-guard   File: SqlServerMaxValueIncrementer.java   View Source Code Vote up 4 votes
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that @@identity
		* returnes the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate("insert into " + getIncrementerName() + " default values");
				ResultSet rs = stmt.executeQuery("select @@identity");
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("@@identity failed after executing an update");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			long maxValue = this.valueCache[(this.valueCache.length - 1)];
			stmt.executeUpdate("delete from " + getIncrementerName() + " where " + getColumnName() + " < " + maxValue);
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not increment identity", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 71
Project: class-guard   File: DerbyMaxValueIncrementer.java   View Source Code Vote up 4 votes
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same connection (otherwise we can't be sure that last_insert_id()
		* returned the correct value)
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate("insert into " + getIncrementerName() + " (" + getDummyName() + ") values(null)");
				ResultSet rs = stmt.executeQuery("select IDENTITY_VAL_LOCAL() from " + getIncrementerName());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("IDENTITY_VAL_LOCAL() failed after executing an update");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			long maxValue = this.valueCache[(this.valueCache.length - 1)];
			stmt.executeUpdate("delete from " + getIncrementerName() + " where " + getColumnName() + " < " + maxValue);
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not obtain IDENTITY value", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 72
Project: class-guard   File: HsqlMaxValueIncrementer.java   View Source Code Vote up 4 votes
@Override
protected synchronized long getNextKey() throws DataAccessException {
	if (this.nextValueIndex < 0 || this.nextValueIndex >= getCacheSize()) {
		/*
		* Need to use straight JDBC code because we need to make sure that the insert and select
		* are performed on the same Connection. Otherwise we can't be sure that last_insert_id()
		* returned the correct value.
		*/
		Connection con = DataSourceUtils.getConnection(getDataSource());
		Statement stmt = null;
		try {
			stmt = con.createStatement();
			DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
			this.valueCache = new long[getCacheSize()];
			this.nextValueIndex = 0;
			for (int i = 0; i < getCacheSize(); i++) {
				stmt.executeUpdate("insert into " + getIncrementerName() + " values(null)");
				ResultSet rs = stmt.executeQuery("select max(identity()) from " + getIncrementerName());
				try {
					if (!rs.next()) {
						throw new DataAccessResourceFailureException("identity() failed after executing an update");
					}
					this.valueCache[i] = rs.getLong(1);
				}
				finally {
					JdbcUtils.closeResultSet(rs);
				}
			}
			long maxValue = this.valueCache[(this.valueCache.length - 1)];
			stmt.executeUpdate("delete from " + getIncrementerName() + " where " + getColumnName() + " < " + maxValue);
		}
		catch (SQLException ex) {
			throw new DataAccessResourceFailureException("Could not obtain identity()", ex);
		}
		finally {
			JdbcUtils.closeStatement(stmt);
			DataSourceUtils.releaseConnection(con, getDataSource());
		}
	}
	return this.valueCache[this.nextValueIndex++];
}
 
Example 73
Project: JServer   File: JdbcDaoComponent.java   View Source Code Vote up 4 votes
/**
 * Get a JDBC Connection, either from the current transaction or a new one.
 */
protected final Connection getConnection() throws CannotGetJdbcConnectionException 
{
   return DataSourceUtils.getConnection(getDataSource());
}
 
Example 74
Project: springapp   File: SpringConnectionProvider.java   View Source Code Vote up 4 votes
@Override
public Connection get() {
	return DataSourceUtils.getConnection(dataSource);
}
 
Example 75
Project: syncope   File: LoggerLoader.java   View Source Code Vote up 4 votes
@Override
public Connection getConnection() throws SQLException {
    return DataSourceUtils.getConnection(dataSource);
}
 
Example 76
Project: dbflute-example-on-springboot   File: DBFluteConfig.java   View Source Code Vote up 4 votes
public Connection getConnectionFromUtils(DataSource ds) {
    return DataSourceUtils.getConnection(ds);
}
 
Example 77
Project: javersion   File: PersistenceTestConfiguration.java   View Source Code Vote up 4 votes
@Bean
public SQLQueryFactory queryFactory(final DataSource dataSource, com.querydsl.sql.Configuration configuration) {
    return new SQLQueryFactory(configuration, () -> DataSourceUtils.getConnection(dataSource));
}
 
Example 78
Project: javersion   File: JsonStoreApplication.java   View Source Code Vote up 4 votes
@Bean
public SQLQueryFactory queryFactory(final DataSource dataSource) {
    com.mysema.query.sql.Configuration configuration = new com.mysema.query.sql.Configuration(new H2Templates());
    ObjectVersionStoreJdbc.registerTypes(configuration);
    return new SQLQueryFactory(configuration, () -> DataSourceUtils.getConnection(dataSource));
}
 
Example 79
Project: CommonDao   File: JdbcTxCommonDao.java   View Source Code Vote up 4 votes
/**
 * 添加支持jdbc datasource Transaction 支持的Connection获取
 */
@Override
protected Connection getConnection() throws SQLException {
	return DataSourceUtils.getConnection(dataSource);
}
 
Example 80
Project: egovframework.rte.root   File: SpringDatabaseDataSourceConnection.java   View Source Code Vote up 4 votes
/**
 * @see org.dbunit.database.IDatabaseConnection#getConnection()
 */
public Connection getConnection() throws SQLException {
    return DataSourceUtils.getConnection(dataSource);
}
 
Example 81
Project: egovframework.rte.root   File: SpringDatabaseDataSourceConnection.java   View Source Code Vote up 4 votes
/**
 * @see org.dbunit.database.IDatabaseConnection#getConnection()
 */
public Connection getConnection() throws SQLException {
    return DataSourceUtils.getConnection(dataSource);
}
 
Example 82
Project: lams   File: JdbcDaoSupport.java   View Source Code Vote up 2 votes
/**
 * Get a JDBC Connection, either from the current transaction or a new one.
 * @return the JDBC Connection
 * @throws CannotGetJdbcConnectionException if the attempt to get a Connection failed
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)
 */
protected final Connection getConnection() throws CannotGetJdbcConnectionException {
	return DataSourceUtils.getConnection(getDataSource());
}
 
Example 83
Project: spring4-understanding   File: JdbcDaoSupport.java   View Source Code Vote up 2 votes
/**
 * Get a JDBC Connection, either from the current transaction or a new one.
 * @return the JDBC Connection
 * @throws CannotGetJdbcConnectionException if the attempt to get a Connection failed
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)
 */
protected final Connection getConnection() throws CannotGetJdbcConnectionException {
	return DataSourceUtils.getConnection(getDataSource());
}
 
Example 84
Project: leopard   File: JdbcDaoSupport.java   View Source Code Vote up 2 votes
/**
 * Get a JDBC Connection, either from the current transaction or a new one.
 * 
 * @return the JDBC Connection
 * @throws CannotGetJdbcConnectionException
 *             if the attempt to get a Connection failed
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)
 */
protected final Connection getConnection() throws CannotGetJdbcConnectionException {
	return DataSourceUtils.getConnection(getDataSource());
}
 
Example 85
Project: leopard-data   File: JdbcDaoSupport.java   View Source Code Vote up 2 votes
/**
 * Get a JDBC Connection, either from the current transaction or a new one.
 * 
 * @return the JDBC Connection
 * @throws CannotGetJdbcConnectionException
 *             if the attempt to get a Connection failed
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)
 */
protected final Connection getConnection() throws CannotGetJdbcConnectionException {
	return DataSourceUtils.getConnection(getDataSource());
}
 
Example 86
Project: class-guard   File: JdbcDaoSupport.java   View Source Code Vote up 2 votes
/**
 * Get a JDBC Connection, either from the current transaction or a new one.
 * @return the JDBC Connection
 * @throws CannotGetJdbcConnectionException if the attempt to get a Connection failed
 * @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)
 */
protected final Connection getConnection() throws CannotGetJdbcConnectionException {
	return DataSourceUtils.getConnection(getDataSource());
}
 
Example 87
Project: fixflow   File: DBConnFactory.java   View Source Code Vote up 2 votes
/**
  * createConnection

  * @Title: createConnection
  * @param @return
  * @param @throws SQLException    设定文件
  * @return Connection    返回类型
  * @throws
  */
public Connection createConnection() throws SQLException{
	Connection connection = DataSourceUtils.getConnection(dataSource);
	return connection;
}