📄 datasourceutils.java
字号:
/*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.datasource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jndi.JndiLocatorSupport;
import org.springframework.jndi.JndiTemplate;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.Assert;
/**
* Helper class that provides static methods to obtain connections from
* JNDI and close connections if necessary. Has support for thread-bound
* connections, e.g. for use with DataSourceTransactionManager.
*
* <p>Note: The <code>getDataSourceFromJndi</code> methods are targetted at
* applications that do not use a Spring BeanFactory. With the latter, it is
* preferable to preconfigure your beans or even JdbcTemplate instances in the
* factory: JndiObjectFactoryBean can be used to fetch a DataSource from JNDI
* and pass the DataSource bean reference to other beans. Switching to another
* DataSource is just a matter of configuration then: For example, you can
* replace the definition of the JndiObjectFactoryBean with a local DataSource
* (like a Commons DBCP BasicDataSource).
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see #getDataSourceFromJndi
* @see org.springframework.jndi.JndiObjectFactoryBean
* @see #getConnection
* @see DataSourceTransactionManager
*/
public abstract class DataSourceUtils {
/**
* Order value for TransactionSynchronization objects that clean up
* JDBC Connections.
*/
public static final int CONNECTION_SYNCHRONIZATION_ORDER = 1000;
private static final Log logger = LogFactory.getLog(DataSourceUtils.class);
/**
* Look up the specified DataSource in JNDI, assuming that the lookup
* occurs in a J2EE container, i.e. adding the prefix "java:comp/env/"
* to the JNDI name if it doesn't already contain it.
* <p>Use getDataSourceFromJndi(jndiName,false) in case of a custom JNDI name.
* @param jndiName jndiName of the DataSource
* @return the DataSource
* @throws org.springframework.jdbc.CannotGetJdbcConnectionException
* if the data source cannot be located
* @deprecated in favor of managing a DataSource via dependency injection,
* i.e. using a JndiObjectFactoryBean for a JNDI DataSource and pass a
* bean reference to a setDataSource(DataSource) method or the like
* @see #getDataSourceFromJndi(String, boolean)
* @see org.springframework.jndi.JndiObjectFactoryBean
*/
public static DataSource getDataSourceFromJndi(String jndiName)
throws CannotGetJdbcConnectionException {
return getDataSourceFromJndi(jndiName, true);
}
/**
* Look up the specified DataSource in JNDI, explicitly specifying
* if the lookup occurs in a J2EE container.
* @param jndiName jndiName of the DataSource
* @param resourceRef if the lookup occurs in a J2EE container, i.e. if the prefix
* "java:comp/env/" needs to be added if the JNDI name doesn't already contain it.
* @return the DataSource
* @throws org.springframework.jdbc.CannotGetJdbcConnectionException
* if the data source cannot be located
* @deprecated in favor of managing a DataSource via dependency injection,
* i.e. using a JndiObjectFactoryBean for a JNDI DataSource and pass a
* bean reference to a setDataSource(DataSource) method or the like
* @see org.springframework.jndi.JndiObjectFactoryBean
*/
public static DataSource getDataSourceFromJndi(String jndiName, boolean resourceRef)
throws CannotGetJdbcConnectionException {
Assert.hasText(jndiName, "JNDI name must not be empty");
if (resourceRef && !jndiName.startsWith(JndiLocatorSupport.CONTAINER_PREFIX)) {
jndiName = JndiLocatorSupport.CONTAINER_PREFIX + jndiName;
}
try {
// Perform JNDI lookup to obtain resource manager connection factory
return (DataSource) new JndiTemplate().lookup(jndiName);
}
catch (NamingException ex) {
throw new CannotGetJdbcConnectionException(
"Naming exception looking up JNDI data source [" + jndiName + "]", ex);
}
}
/**
* Get a Connection from the given DataSource. Changes any SQL exception into
* the Spring hierarchy of unchecked generic data access exceptions, simplifying
* calling code and making any exception that is thrown more meaningful.
* <p>Is aware of a corresponding Connection bound to the current thread, for example
* when using DataSourceTransactionManager. Will bind a Connection to the thread
* if transaction synchronization is active (e.g. if in a JTA transaction).
* @param dataSource DataSource to get Connection from
* @return a JDBC Connection from this DataSource
* @throws org.springframework.jdbc.CannotGetJdbcConnectionException
* if the attempt to get a Connection failed
* @see org.springframework.transaction.support.TransactionSynchronizationManager
* @see DataSourceTransactionManager
*/
public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException {
return getConnection(dataSource, true);
}
/**
* Get a Connection from the given DataSource. Changes any SQL exception into
* the Spring hierarchy of unchecked generic data access exceptions, simplifying
* calling code and making any exception that is thrown more meaningful.
* <p>Is aware of a corresponding Connection bound to the current thread, for example
* when using DataSourceTransactionManager. Will bind a Connection to the thread
* if transaction synchronization is active (e.g. if in a JTA transaction).
* @param dataSource DataSource to get Connection from
* @param allowSynchronization if a new JDBC Connection is supposed to be
* registered with transaction synchronization (if synchronization is active).
* This will always be true for typical data access code.
* @return a JDBC Connection from this DataSource
* @throws org.springframework.jdbc.CannotGetJdbcConnectionException
* if the attempt to get a Connection failed
* @see #doGetConnection
* @see org.springframework.transaction.support.TransactionSynchronizationManager
* @see DataSourceTransactionManager
*/
public static Connection getConnection(DataSource dataSource, boolean allowSynchronization)
throws CannotGetJdbcConnectionException {
try {
return doGetConnection(dataSource, allowSynchronization);
}
catch (SQLException ex) {
throw new CannotGetJdbcConnectionException("Could not get JDBC connection", ex);
}
}
/**
* Actually get a JDBC Connection for the given DataSource.
* Same as getConnection, but throwing the original SQLException.
* <p>Directly accessed by TransactionAwareDataSourceProxy.
* @param dataSource DataSource to get Connection from
* @param allowSynchronization if a new JDBC Connection is supposed to be
* registered with transaction synchronization (if synchronization is active).
* This will always be true for typical data access code.
* @return a JDBC Connection from this DataSource
* @throws SQLException if thrown by JDBC methods
* @see #getConnection(DataSource, boolean)
* @see TransactionAwareDataSourceProxy
*/
protected static Connection doGetConnection(DataSource dataSource, boolean allowSynchronization)
throws SQLException {
Assert.notNull(dataSource, "No DataSource specified");
ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
if (conHolder != null) {
conHolder.requested();
return conHolder.getConnection();
}
logger.debug("Opening JDBC connection");
Connection con = dataSource.getConnection();
if (allowSynchronization && TransactionSynchronizationManager.isSynchronizationActive()) {
logger.debug("Registering transaction synchronization for JDBC connection");
// use same Connection for further JDBC actions within the transaction
// thread object will get removed by synchronization at transaction completion
conHolder = new ConnectionHolder(con);
TransactionSynchronizationManager.bindResource(dataSource, conHolder);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -