Glassfish:JDBC 池中的 "Non Transactional Settings" 选项

Glassfish : "Non Transactional Settings" option in JDBC Pools

在 Glassfish 中,有一个名为

的 JDBC 池选项

Non Transactional Connections

那么我认为 "Non Transactional Connections" 与设置 auto-commit=false 相同的想法是否正确?

如果那是正确的,那么为什么当这个选项被禁用(即非事务启用)时我会收到一条错误消息说

org.postgresql.util.PSQLException: Cannot commit when autoCommit is enabled.

此时我的 java 代码看起来像:

try {
preparedStatement = connection.prepareStatement(.....);
preparedStatement.executeQuery();
connection.commit();
}

非事务性连接默认情况下不会将 autoCommit 属性 设置为 false。这不是非事务性连接的目的。来自下面的 Oracle glassfish 文档,

The main advantage of using non-transactional connections is that the overhead incurred in enlisting and delisting connections in transaction contexts is avoided. However, use such connections carefully. For example, if a non-transactional connection is used to query the database while a transaction is in progress that modifies the database, the query retrieves the unmodified data in the database. This is because the in-progress transaction hasn’t committed. For another example, if a non-transactional connection modifies the database and a transaction that is running simultaneously rolls back, the changes made by the non-transactional connection are not rolled back.

你应该

Connection con = ds.getConnection();
boolean initValue = con.getAutoCommit(); 
con.setAutoCommit(false);
//do your work here and commit or rollback
con.setAutoCommit(initValue );