JDBC 事务有问题。不能让它成为原子性

Problem with JDBC transaction. Can't make it atomicity

我有代码:

 @Override
    public void update(Duck entity) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
       try {
            connection = DriverManager.getConnection(daoProperties.getUrl(), daoProperties.getUser(), daoProperties.getPassword());
            connection.setAutoCommit(false);
            connection.commit()
            preparedStatement = connection.prepareStatement(INSERT_FROG);

            preparedStatement.setInt(ID, entity.getFrogId());
            preparedStatement.setString(NAME, entity.getMyFrogFriend().name());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

        try {
            PreparedStatement duckPreparedStatement = connection.prepareStatement(INSERT_DUCK);

            duckPreparedStatement.setInt(ID, entity.id());
            //..
            duckPreparedStatement.executeUpdate();
   //         throw new SQLException();
    //        connection.commit();
        } catch (SQLException e) {
            log.warning("error with statements or connection");
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

我想,如果第二次插入失败,那么我们不执行第一次插入。但是这段代码不起作用,如果我们要删除第一条评论,那么首先插入将完成。我做错了什么?

try-catchrollback 应该覆盖整个工作单元。现在您正在第一次失败后回滚,然后继续,就好像什么也没发生一样。结果,第二个插入将在它自己的事务中(因此与第一个不同的事务),并单独成功。

相反,您需要在两个语句(整个事务)之后回滚,而不是每个语句。

try {
    // first insert
    // second insert
} catch (SQLException e) {
    connection.rollback();
}

顺便说一句,在 之前 commit() 你的工作单元是没有意义的,并且似乎表明整个事务管理被破坏了。您在工作单元后注释掉 commit() 的事实也是不可取的。如果连接关闭,您的事务将被回滚(或某些数据库:已提交),如果您的连接被重用,工作将被提交或回滚,具体取决于重用该连接的后续代码将执行的操作。