下面列出了org.quartz.SchedulerConfigException#org.springframework.jdbc.datasource.DataSourceUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
/**
* 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);
}
}
/**
* 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());
}
}
@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());
}
}
/**
* 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());
}
}
/**
* 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);
}
}
/**
* 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());
}
}
@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());
}
}
@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());
}
/**
*/
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);
}
@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)
{
}
}
}
/**
* 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);
}
}
/**
* 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());
}
}
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);
}
}
@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;
}
@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);
}
}
}
@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);
}
}
public void closeAndRockBack() throws SQLException{
if (connection != null && connection.isClosed()==false){
if(connection.getAutoCommit()==false){
connection.rollback();
}
DataSourceUtils.releaseConnection(connection, dataSource);
}
}
@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++];
}
@Override
@Nullable
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
T result = action.doInStatement(stmt);
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.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallback", sql, ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
@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());
}
}
/**
* 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);
}
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);
}
/**
* 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);
}
private void openMainConnection() throws SQLException {
this.mainConnection = DataSourceUtils.getConnection(this.dataSource);
this.autoCommit = this.mainConnection.getAutoCommit();
this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.mainConnection, this.dataSource);
if (log.isDebugEnabled()) {
log.debug("Sundial JDBC Connection [" + this.mainConnection + "] will" +
(this.isConnectionTransactional ? " " : " not ") + "be managed by Spring");
}
}
@NonNull
@Override
public Connection getConnection() {
try {
Connection connection = DataSourceUtils.doGetConnection(dataSource);
if (DataSourceUtils.isConnectionTransactional(connection, dataSource)) {
return connection;
} else {
connection.close();
throw new NoTransactionException("No transaction declared. Define @Transactional on the surrounding method prior to calling getConnection()");
}
} catch (SQLException e) {
throw new DataAccessException("Error retrieving JDBC connection: " + e.getMessage(), e);
}
}
@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++];
}
@Override
@Nullable
public <T> T execute(StatementCallback<T> action) throws DataAccessException {
Assert.notNull(action, "Callback object must not be null");
Connection con = DataSourceUtils.getConnection(obtainDataSource());
Statement stmt = null;
try {
stmt = con.createStatement();
applyStatementSettings(stmt);
T result = action.doInStatement(stmt);
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.
String sql = getSql(action);
JdbcUtils.closeStatement(stmt);
stmt = null;
DataSourceUtils.releaseConnection(con, getDataSource());
con = null;
throw translateException("StatementCallback", sql, ex);
}
finally {
JdbcUtils.closeStatement(stmt);
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
/**
* 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());
}
/**
* 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);
}