Can I set the JDBC isolation level from a Tomcat C

2020-03-26 07:04发布

问题:

I have a web application running in Tomcat 6, and I've managed to configure it to use the built-in DBCP connection pooling, and all is working very well, however I suspect it is running in the wrong isolation level on the database. I'd like it to run in read uncommitted, but I think it's running in read committed and don't know how to set it.

Here is my context's XML file:

<?xml version="1.0" encoding="UTF-8"?>
    <Context antiResourceLocking="false" privileged="true">
        <Resource 
            name="jdbc/Connection" 
            auth="Container" 
            type="javax.sql.DataSource"
            maxActive="100" 
            maxIdle="30" 
            maxWait="10000"
            driverClassName="net.sourceforge.jtds.jdbc.Driver"
            url="jdbc:jtds:sqlserver://...etc..."
        />
    </Context>

And this is the Java method used to get a database connection.

public Connection getDatabaseConnection() throws ServletException {
    try {
        InitialContext cxt = new InitialContext();
        if ( cxt == null ) {
            throw new ServletException( "ServletContext unavailable." );
        }

        DataSource ds = (DataSource)cxt.lookup( "java:/comp/env/jdbc/Connection" );
        if ( ds == null ) {
            throw new ServletException( "Data source not found!" );
        }

        Connection conn = ds.getConnection();
        return conn;
    } etc...

Having obtained the connection in getDatabaseConnection() I realise I could manually set the isolation level with conn.setIsolationLevel( Connection.TRANSACTION_READ_UNCOMMITTED ) but that feels wrong as it either involves hard-coding the isolation level into the Java, or performing a look-up to the servlet context every time a new connection is required.

Can I define this in the context XML somehow, or is there a better approach I'm not aware of?

回答1:

Yes, you can set that with defaultTransactionIsolation attribute in the Resource element.

<Context antiResourceLocking="false" privileged="true">
        <Resource 
            defaultTransactionIsolation="READ_UNCOMMITTED"
            name="jdbc/Connection" 
            auth="Container" 
            type="javax.sql.DataSource"
            maxActive="100" 
            maxIdle="30" 
            maxWait="10000"
            driverClassName="net.sourceforge.jtds.jdbc.Driver"
            url="jdbc:jtds:sqlserver://...etc..."
        />

From the docs:

defaultTransactionIsolation¨

TransactionIsolation state of connections created by this pool. One of the following: (see javadoc )

  • NONE
  • READ_COMMITTED
  • READ_UNCOMMITTED
  • REPEATABLE_READ
  • SERIALIZABLE


回答2:

I was looking for snapshot isolation level. The setting which was reported correctly by the database server was

defaultTransactionIsolation="4096"

You may confirm by a query to sys.dm_exec_sessions which should report transaction_isolation_level = 5. Hope it helps someone.