Java more than one DB connection in UserTransaction

前端 未结 5 789
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 23:12
static void clean() throws Exception {
  final UserTransaction tx = InitialContext.doLookup(\"UserTransaction\");
  tx.begin();

  try {
    final DataSource ds = In         


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-01-19 23:35

    My guess is that you have autocommit enabled on the connections. This is the default when creating a new connection, as is documented here https://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html

    System.out.println(connection1.getAutoCommit());
    

    will most likely print true.

    You could try

    connection1.setAutoCommit(false); 
    

    and see if that changes the behavior.

    In addition to that, it's not really defined what happens if you call close() on a connection and haven't issued a commit or rollback statement beforehand. Therefore it is strongly recommended to either issue one of the two before closing the connection, see https://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#close()

    EDIT 1: If autocommit is false, the it's probably due to the undefined behavior of close. What happens if you switch the statements? :

    st2.executeUpdate();
    st2.close();
    connection2.close();
    st1.executeUpdate();
    st1.close();
    connection1.close();
    

    EDIT 2: You could also try the "correct" way of doing it:

    st1.executeUpdate();
    st1.close();
    st2.executeUpdate();
    st2.close();
    tx.commit();
    connection1.close();
    connection2.close();
    

    If that doesn't fail, then something is wrong with your setup for UserTransactions.

提交回复
热议问题