我正在使用 postgresql 9.2 和 C3p0 0.9.2.1,我创建了一个连接定制器来禁用autoCommit
和设置transactionMode
,但是当我进行查找InitialContext
以检索 时dataSource
,autoCommit
连接上并没有禁用(登录底部)。如何禁用自动提交?
连接定制器:
public class IsolationLevelConnectionCustomizer extends
AbstractConnectionCustomizer {
@Override
public void onAcquire(Connection c, String parentDataSourceIdentityToken)
throws Exception {
super.onAcquire(c, parentDataSourceIdentityToken);
System.out.println("Connection acquired, set autocommit off and repeatable read transaction mode.");
c.setAutoCommit(false);
c.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
}
}
为 DAO 检索数据源的类:
public class DAOAcquire {
private ComboPooledDataSource m_cpdsDataSource = null;
private static final String LOOKUP_CONNECT = "jdbc/mydb";
public DAOAcquire() throws NamingException {
InitialContext context = new InitialContext();
m_cpdsDataSource = (ComboPooledDataSource) context.lookup(LOOKUP_CONNECT);
if (m_cpdsDataSource != null) {
try {
System.out.println("Autocommit = "+String.valueOf(m_cpdsDataSource.getConnection().getAutoCommit()));
} catch (SQLException e) {
System.out.println("Could not get autocommit value : "+e.getMessage());
e.printStackTrace();
}
}
}
public ComboPooledDataSource getComboPooledDataSource() {
return m_cpdsDataSource;
}
/**
* @return the jdbcTemplate
* @throws NamingException
*/
public JdbcTemplate getJdbcTemplate() throws NamingException {
return new JdbcTemplate(m_cpdsDataSource);
}
/**
* Commit transactions
* @throws SQLException
*/
public void commit() throws SQLException {
if (m_cpdsDataSource != null) {
m_cpdsDataSource.getConnection().commit();
} else {
throw new SQLException("Could not commit. Reason : Unable to connect to database, dataSource is null.");
}
}
/**
* rollback all transactions to previous save point
* @throws SQLException
*/
public void rollback() throws SQLException {
if (m_cpdsDataSource != null) {
m_cpdsDataSource.getConnection().rollback();
} else {
throw new SQLException("Could not rollback. Reason : Unable to connect to database, dataSource is null.");
}
}
}
日志 :
Connection acquired, set autocommit off and repeatable read transaction mode.
Connection acquired, set autocommit off and repeatable read transaction mode.
Connection acquired, set autocommit off and repeatable read transaction mode.
Autocommit = true
默认情况下,postgresql 自动提交模式是禁用的,那么为什么 c3p0 会自动激活它呢?我应该将 forceIgnoreUnresolvedTransactions 设置为 true 吗?
编辑:每当我在检索数据源后提交事务时,都会收到此错误:
org.postgresql.util.PSQLException: Cannot commit when autoCommit is enabled.