How to start a transaction in JDBC?

后端 未结 8 1110
梦谈多话
梦谈多话 2020-12-02 08:48

Connection.setTransactionIsolation(int) warns:

Note: If this method is called during a transaction, the result is implementation-defined.

相关标签:
8条回答
  • 2020-12-02 09:28

    Actually, this page from the JDBC tutorial would be a better read.
    You would get your connection, set your isolation level and then do your updates amd stuff and then either commit or rollback.

    0 讨论(0)
  • 2020-12-02 09:38

    Answering my own question:

    • JDBC connections start out with auto-commit mode enabled, where each SQL statement is implicitly demarcated with a transaction.
    • Users who wish to execute multiple statements per transaction must turn auto-commit off.
    • Changing the auto-commit mode triggers a commit of the current transaction (if one is active).
    • Connection.setTransactionIsolation() may be invoked anytime if auto-commit is enabled.
    • If auto-commit is disabled, Connection.setTransactionIsolation() may only be invoked before or after a transaction. Invoking it in the middle of a transaction leads to undefined behavior.

    Sources:

    • Javadoc
    • JDBC Tutorial
    0 讨论(0)
  • 2020-12-02 09:40

    You can use these methods for transaction:

    1. you must create the connection object like con
    2. con.setAutoCommit(false);
    3. your queries
    4. if all is true con.commit();
    5. else con.rollback();
    0 讨论(0)
  • 2020-12-02 09:43

    Startingly, you can manually run a transaction, if you wish to leave your connection in "setAutoCommit(true)" mode but still want a transaction:

     try (Statement statement = conn.createStatement()) {
          statement.execute("BEGIN");
          try {
            // use statement ...
            statement.execute("COMMIT");
          }
          catch (SQLException failure) {
            statement.execute("ROLLBACK");
          }
      }
    
    0 讨论(0)
  • 2020-12-02 09:44

    Using one connection for multiple transactions (reuse, pooling or chaining) some weird problems can lurk creating problems people have to live by since they usually cant identify the causes.

    The following scenarios come to mind:

    1. (Re-)Using a connection with an ongoing / uncommitted transaction
    2. Flawed connection pool implementations
    3. Higher isolation level implementations in some databases (especially the distributed SQL and the NoSQL one)

    Point 1 is straight forward and understandable. Point 2 basically leads to either point 1 or (and) point 3.

    Point 3 is all about a system where a new transaction has begun before the first statement is issued. From a database perspective such a transaction might have started long before the 'first' real statement was issued. If the concurrency model is based on the snapshot idea where one reads only states/values that were valid at the point the transaction begins but no change that has changed later on, it is very important that on commit the full read set of the current transaction is also validated.

    Since NoSQL and certain isolation levels like MS SQL-Server Snapshot often do not validate the read-set (in the right way), all bets are usually off to what to expect. While this is a problem always being present, it is way worse when one is dealing with transactions that start on the last commit or when the connection was pooled rather than the connection being actually used, it is usually important to make sure the transaction actually starts when it is expected to start. (Also very important if one uses a rollback-only read-only transaction).

    I use the following rules when dealing with JDBC in JAVA:

    1. Always rollback a JDBC connection before using it (scraps everyting and starts a new transaction), if the company uses plain JDBC in conjunction with any pooling mechanism
    2. Use Hibernate for Transaction handling even if only using a session managed JDBC connection for plain SQL. Never had a problem with transactions till now.
    3. Use BEGIN / COMMIT / ROLLBACK as SQL-Statements (like already mentioned). Most implementations will fail if you issue a BEGIN statement during an active transaction (test it for your database and remember the test database is not the production database and JDBC Driver and JDBC Server-side implementations can differ in behaviro than running a SQL console on the actual server).
    4. Use 3 inside one's own wrapper for a JDBC connection instances. This way transaction handling is always correct (if no reflection is used and the connection pooling is not flawed).

    3+4 I only use if response time is critical or if Hibernate is not available. 4 allows for using some more advanced performance (response time) improvement patterns for special cases

    0 讨论(0)
  • 2020-12-02 09:48

    JDBC implicitly demarcates each query/update you perform on the connection with a transaction. You can customize this behavior by calling setAutoCommit(false) to turn off the auto-commit mode and call the commit()/rollback() to indicate the end of a transaction. Pesudo code

    try
    {
      con.setAutoCommit(false);
    
       //1 or more queries or updates
    
       con.commit();
    }
    catch(Exception e)
    {
       con.rollback();
    }
    finally
    {
       con.close();
    }
    

    Now, there is a type in the method you have shown. It should be setTransactionIsolation(int level) and is not the api for transaction demarcation. It manages how/when the changes made by one operation become visible to other concurrent operations, the "I" in ACID (http://en.wikipedia.org/wiki/Isolation_(database_systems))

    0 讨论(0)
提交回复
热议问题