org.springframework.jdbc.datasource.DataSourceUtils Java Examples

The following examples show how to use org.springframework.jdbc.datasource.DataSourceUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DynamicSpringManagedTransaction.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: AbstractSequenceMaxValueIncrementer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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 #3
Source File: JdbcTemplate.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public <T> T execute(ConnectionCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(obtainDataSource());
	try {
		// Create close-suppressing Connection proxy, also preparing returned Statements.
		Connection 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.
		String sql = getSql(action);
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw translateException("ConnectionCallback", sql, ex);
	}
	finally {
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #4
Source File: AbstractSequenceMaxValueIncrementer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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
Source File: ProvisioningImpl.java    From syncope with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: DatabasePopulatorUtils.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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 not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	try {
		Connection connection = DataSourceUtils.getConnection(dataSource);
		try {
			populator.populate(connection);
		}
		finally {
			DataSourceUtils.releaseConnection(connection, dataSource);
		}
	}
	catch (Throwable ex) {
		if (ex instanceof ScriptException) {
			throw (ScriptException) ex;
		}
		throw new UncategorizedScriptException("Failed to execute database script", ex);
	}
}
 
Example #7
Source File: HibernateJpaDialect.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
public void resetSessionState() {
	if (this.previousFlushMode != null) {
		this.session.setFlushMode(this.previousFlushMode);
	}
	if (this.preparedCon != null && this.session.isConnected()) {
		Connection conToReset = HibernateConnectionHandle.doGetConnection(this.session);
		if (conToReset != this.preparedCon) {
			LogFactory.getLog(HibernateJpaDialect.class).warn(
					"JDBC Connection to reset not identical to originally prepared Connection - please " +
					"make sure to use connection release mode ON_CLOSE (the default) and to run against " +
					"Hibernate 4.2+ (or switch HibernateJpaDialect's prepareConnection flag to false");
		}
		DataSourceUtils.resetConnectionAfterTransaction(conToReset, this.previousIsolationLevel);
	}
}
 
Example #8
Source File: AbstractSequenceMaxValueIncrementer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #9
Source File: DatabasePopulatorUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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 not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	try {
		Connection connection = DataSourceUtils.getConnection(dataSource);
		try {
			populator.populate(connection);
		}
		finally {
			DataSourceUtils.releaseConnection(connection, dataSource);
		}
	}
	catch (Throwable ex) {
		if (ex instanceof ScriptException) {
			throw (ScriptException) ex;
		}
		throw new UncategorizedScriptException("Failed to execute database script", ex);
	}
}
 
Example #10
Source File: JdbcTemplate.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
@Nullable
public <T> T execute(ConnectionCallback<T> action) throws DataAccessException {
	Assert.notNull(action, "Callback object must not be null");

	Connection con = DataSourceUtils.getConnection(obtainDataSource());
	try {
		// Create close-suppressing Connection proxy, also preparing returned Statements.
		Connection 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.
		String sql = getSql(action);
		DataSourceUtils.releaseConnection(con, getDataSource());
		con = null;
		throw translateException("ConnectionCallback", sql, ex);
	}
	finally {
		DataSourceUtils.releaseConnection(con, getDataSource());
	}
}
 
Example #11
Source File: JdbcTransactionRepository.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
protected int doDelete(TransactionInfo transactionInfo) {

		Connection conn= DataSourceUtils.getConnection(dataSourceAdaptor.getDataSource());
		PreparedStatement stmt = null;

		try {

			StringBuilder builder = new StringBuilder();
			builder.append("DELETE FROM TRANSACTION_INFO " + " WHERE TX_ID = ?");

			stmt = conn.prepareStatement(builder.toString());

			stmt.setLong(1, transactionInfo.getTxId());

			return stmt.executeUpdate();

		} catch (SQLException e) {
			throw new DistributedTransactionException(e);
		} finally {
			closeStatement(stmt);
			releaseConnection(conn);
		}
	}
 
Example #12
Source File: HibernateExtendedJpaDialect.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@Override
 public Object beginTransaction(final EntityManager entityManager, 
 		final TransactionDefinition definition) throws PersistenceException, SQLException, TransactionException {
 	
 	Session session = (Session) entityManager.getDelegate();
 	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
 		getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
 	}
 	entityManager.getTransaction().begin();
 	logger.debug("Transaction started");
 	session.doWork(new Work() {
@Override
public void execute(Connection connection) throws SQLException {
	 logger.debug("The connection instance is " + connection.toString());
	 logger.debug("The isolation level of the connection is " + connection.getTransactionIsolation() 
			 + " and the isolation level set on the transaction is " + definition.getIsolationLevel() );
	 DataSourceUtils.prepareConnectionForTransaction(connection, definition);
}
 	});
 	return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
 }
 
Example #13
Source File: CacheSpringStoreSessionListenerSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 */
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 #14
Source File: DialectFactoryBean.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Dialect getObject() throws SQLException
{
    Connection con = null;
    try
    {
        // make sure that we AUTO-COMMIT
        con = DataSourceUtils.getConnection(dataSource);
        con.setAutoCommit(true);
        DatabaseMetaData meta = con.getMetaData();
        Dialect dialect = DialectFactory.buildDialect(meta.getDatabaseProductName(), meta.getDatabaseMajorVersion(), meta.getDriverName());
        return dialect;
    }
    finally
    {
        try
        {
            con.close();
        }
        catch (Exception e)
        {
        }
    }
}
 
Example #15
Source File: DefaultJdbcExecutor.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void releaseConnection(Connection connection) throws SQLException {
    if (logger.isDebugEnabled()) {
        logger.debug("Releasing DataSource ({}) JDBC Connection [{}]", getDatasourceId(), connection);
    }
    try {
        DataSourceUtils.doReleaseConnection(connection, DataSourceHolder.currentDataSource().getNative());
    } catch (SQLException e) {
        logger.error(e.getMessage(), e);
        try {
            connection.close();
        } catch (Exception e2) {
            logger.error(e2.getMessage(), e2);
        }
    }
}
 
Example #16
Source File: DatabasePopulatorUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	try {
		Connection connection = DataSourceUtils.getConnection(dataSource);
		try {
			populator.populate(connection);
		}
		finally {
			DataSourceUtils.releaseConnection(connection, dataSource);
		}
	}
	catch (Throwable ex) {
		if (ex instanceof ScriptException) {
			throw (ScriptException) ex;
		}
		throw new UncategorizedScriptException("Failed to execute database script", ex);
	}
}
 
Example #17
Source File: AbstractSequenceMaxValueIncrementer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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 #18
Source File: EtDataSourceManager.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@Override
    public Long branchRegister(BranchType branchType, String resourceId, String clientId, String xid, String applicationData, String lockKey) throws TransactionException {
//        public Long branchRegister(BranchType branchType, String resourceId, String clientId, String xid, String lockKey) throws TransactionException {

        Integer callSeq = MetaDataFilter.getMetaData(EasytransConstant.CallHeadKeys.CALL_SEQ);

        // check locks
        if (StringUtils.isNullOrEmpty(lockKey)) {
            return callSeq== null?-1:callSeq.longValue();
        }

        //ET要求使用Spring管控下的事务,因此本方法可以获得对应的当前连接,获取当前连接来执行时为了避免争夺连接词的连接导致死锁
        DataSourceProxy dataSourceProxy = get(resourceId);
        ConnectionProxy cp = (ConnectionProxy) DataSourceUtils.getConnection(dataSourceProxy);
        Connection targetConnection = cp.getTargetConnection();
        
        if (callSeq != null) {
            // callSeq != null means it's in ET transaction control
            try {
                doLockKeys(xid, lockKey, targetConnection);
            } catch (SQLException e) {
                throw new RuntimeException("Obtain Lock failed, Rollback transaction:" + lockKey, e);
            }

        } else {
            // callSeq == null means it's just a local transaction or a master transaction in ET
            // it need to check lock
            if(!lockQuery(branchType, resourceId, xid, lockKey)) {
                throw new RuntimeException("Obtain Lock failed, Rollback transaction:" + lockKey);
            }
            
            // not need to save undolog ,undo will be handle by local transaction, just hack to clean undo log
            cp.getContext().getUndoItems().clear();
        }
        
        return callSeq== null?-1:callSeq.longValue();
    }
 
Example #19
Source File: LegacyHsqlDaoHelper.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Shutdown the embedded HSQLDB database. After this has run, the database cannot be accessed again from the same DataSource.
 */
private void shutdownHsqldbDatabase() {
    try {
        LOG.debug("Database shutdown in progress...");
        JdbcTemplate jdbcTemplate = getJdbcTemplate();
        try (Connection conn = DataSourceUtils.getConnection(jdbcTemplate.getDataSource())) {
            jdbcTemplate.execute("SHUTDOWN");
        }
        LOG.debug("Database shutdown complete.");

    } catch (SQLException e) {
        LOG.error("Database shutdown failed", e);
    }
}
 
Example #20
Source File: SpringTransactionManager.java    From dalesbred with MIT License 5 votes vote down vote up
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 {
            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);
        }
    });
}
 
Example #21
Source File: JdbcTemplate.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@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
Source File: DBConnection.java    From fixflow with Apache License 2.0 5 votes vote down vote up
public void closeAndRockBack() throws SQLException{
	if (connection != null && connection.isClosed()==false){
		if(connection.getAutoCommit()==false){
			connection.rollback();
		}
		DataSourceUtils.releaseConnection(connection, dataSource);
	}
}
 
Example #23
Source File: SqoopToolJobApplicationTests.java    From spring-cloud-task-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
DatabasePopulator databasePopulator(DataSource dataSource) throws SQLException, InterruptedException {
	DatabasePopulator dbp = new ResourceDatabasePopulator(false, false, "UTF-8",
			new ClassPathResource("sqoop-schema-ddl.sql"),
			new ClassPathResource("sqoop-root-data.sql"),
			new ClassPathResource("sqoop-sessions-data.sql"),
			new ClassPathResource("sqoop-test-schema-ddl.sql"),
			new ClassPathResource("sqoop-test-data.sql"));
	dbp.populate(DataSourceUtils.getConnection(dataSource));
	return dbp;
}
 
Example #24
Source File: RoleAndOrganizationsAspect.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
private static void logEntry(Connection connection, DataSource dataSource,
                                   ProceedingJoinPoint joinPoint,
                                   HttpServletRequest request,
                                   boolean mustCheck,
                                   String formattedOrgIds) {

    StringBuilder sb = new StringBuilder();


    if (connection != null && DataSourceUtils.isConnectionTransactional(connection, dataSource)) {
        sb.append(LINE_SEPARATOR);
        sb.append("connection is transactional\n");
        sb.append("URL IS ").append(request.getRequestURI()).append("\n");
        sb.append(request.getRequestURL()).append("\n");
        sb.append(joinPoint).append("\n");
        sb.append("public url: ").append(isCurrentlyInAPublicUrlRequest()).append("\n");

        if (SecurityContextHolder.getContext() != null && SecurityContextHolder.getContext().getAuthentication() != null) {
            sb.append("auth is ").append(SecurityContextHolder.getContext().getAuthentication().getName()).append("\n");
        } else {
            sb.append("no user\n");
        }

        sb.append("must check row access: ").append(mustCheck).append("\n");

        if(mustCheck) {
            sb.append("org ids are: ").append(formattedOrgIds).append("\n");
        }
        sb.append(LINE_SEPARATOR);

    } else {
        sb.append(LINE_SEPARATOR);
        sb.append("connection is NOT transactional so the check will not be done!\n");
        sb.append("URL IS ").append(request.getRequestURI()).append("\n");
        sb.append(joinPoint).append("\n");
        sb.append(LINE_SEPARATOR);
    }

    log.trace(sb.toString());
}
 
Example #25
Source File: SqoopToolTaskApplicationTests.java    From spring-cloud-task-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
DatabasePopulator databasePopulator(DataSource dataSource) throws SQLException, InterruptedException {
	DatabasePopulator dbp = new ResourceDatabasePopulator(false, false, "UTF-8",
			new ClassPathResource("sqoop-test-schema-ddl.sql"),
			new ClassPathResource("sqoop-test-data.sql"));
	dbp.populate(DataSourceUtils.getConnection(dataSource));
	return dbp;
}
 
Example #26
Source File: HibernateJpaDialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	Session session = getSession(entityManager);

	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
		session.getTransaction().setTimeout(definition.getTimeout());
	}

	boolean isolationLevelNeeded = (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT);
	Integer previousIsolationLevel = null;
	Connection preparedCon = null;

	if (isolationLevelNeeded || definition.isReadOnly()) {
		if (this.prepareConnection) {
			preparedCon = HibernateConnectionHandle.doGetConnection(session);
			previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(preparedCon, definition);
		}
		else if (isolationLevelNeeded) {
			throw new InvalidIsolationLevelException(getClass().getSimpleName() +
					" does not support custom isolation levels since the 'prepareConnection' flag is off. " +
					"This is the case on Hibernate 3.6 by default; either switch that flag at your own risk " +
					"or upgrade to Hibernate 4.x, with 4.2+ recommended.");
		}
	}

	// Standard JPA transaction begin call for full JPA context setup...
	entityManager.getTransaction().begin();

	// Adapt flush mode and store previous isolation level, if any.
	FlushMode previousFlushMode = prepareFlushMode(session, definition.isReadOnly());
	return new SessionTransactionData(session, previousFlushMode, preparedCon, previousIsolationLevel);
}
 
Example #27
Source File: JdbcTemplate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Prepare the given JDBC Statement (or PreparedStatement or CallableStatement),
 * applying statement settings such as fetch size, max rows, and query timeout.
 * @param stmt the JDBC Statement to prepare
 * @throws SQLException if thrown by JDBC API
 * @see #setFetchSize
 * @see #setMaxRows
 * @see #setQueryTimeout
 * @see org.springframework.jdbc.datasource.DataSourceUtils#applyTransactionTimeout
 */
protected void applyStatementSettings(Statement stmt) throws SQLException {
	int fetchSize = getFetchSize();
	if (fetchSize != -1) {
		stmt.setFetchSize(fetchSize);
	}
	int maxRows = getMaxRows();
	if (maxRows != -1) {
		stmt.setMaxRows(maxRows);
	}
	DataSourceUtils.applyTimeout(stmt, getDataSource(), getQueryTimeout());
}
 
Example #28
Source File: DbCommonServiceImpl.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
@Override
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 #29
Source File: DataUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
public static void doReleaseConnection(Connection connection) {
	DataSource dataSource = (DataSource)AppContext.getBean(DATA_SOURCE_BEAN_ID);
	try {
		DataSourceUtils.doReleaseConnection(connection, dataSource);
	} catch (SQLException e) {
		e.printStackTrace();
	}
}
 
Example #30
Source File: JdbcTransactionRepository.java    From tcc-transaction with Apache License 2.0 5 votes vote down vote up
@Override
public List<TransactionInfo> listSince(Date date) {

	Connection conn= DataSourceUtils.getConnection(dataSourceAdaptor.getDataSource());

	List<TransactionInfo> transactionInfos = new ArrayList<TransactionInfo>();

	PreparedStatement stmt = null;

	try {

		StringBuilder builder = new StringBuilder();
		builder.append(SELECT_DQL + " FROM TRANSACTION_INFO WHERE GMT_MODIFIED > ?");

		stmt = conn.prepareStatement(builder.toString());

		stmt.setTimestamp(1, new Timestamp(date.getTime()));

		ResultSet resultSet = stmt.executeQuery();

		while (resultSet.next()) {
			transactionInfos.add(resultSet2Bean(resultSet));
		}
	} catch (Throwable e) {
		throw new DistributedTransactionException(e);
	} finally {
		closeStatement(stmt);
		releaseConnection(conn);
	}

	return transactionInfos;
}