java 开启事务管理,保证数据一致性原创
金蝶云社区-Heaven
Heaven
18人赞赏了该文章 134次浏览 未经作者许可,禁止转载编辑于2024年04月28日 17:28:26

import javax.sql.DataSource;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;


@Service

public class ICStockBillServiceImpl extends ServiceImpl<ICStockBillDao, ICStockBillEntity> implements ICStockBillService {


 @Resource

    private DataSource dataSource;


public void TransactionExample () {

Connection connection = null;

        PreparedStatement statement = null;

        try {

            connection = dataSource.getConnection();

            System.out.println("connection"+connection);

            // 设置自动提交为false,禁用事务自动提交

            connection.setAutoCommit(false);

  // 创建Statement

            statement = connection.createStatement();

            

            // 执行一系列操作

            statement.executeUpdate("INSERT INTO YourTable (column1) VALUES ('value1')");

            statement.executeUpdate("UPDATE YourTable SET column1 = 'newValue' WHERE column1 = 'value1'");

            

            // 提交事务

            connection.commit();

            

            System.out.println("事务成功提交!");

        

        } catch (SQLException e) {

            try {

                if (connection != null) {

                    // 出现异常,回滚事务

                    connection.rollback();

                }

            } catch (SQLException ex) {

                // 处理回滚时的异常

            }

            // 处理其他异常

            throw new RuntimeException("Error performing transaction", e);

        } finally {

            // 关闭资源

            try {

                if (statement != null) statement.close();

                if (connection != null) connection.close();

            } catch (SQLException e) {

                // 处理资源关闭异常

                return "处理资源关闭异常";

            }

        }

}

}

首先加载了数据源DataSource (我这里是通过application.yml配置的。接着,关闭了自动提交事务,以便可以手动控制事务的提交或回滚。在执行SQL操作时,如果出现异常,会进行回滚。最后,在finally块中关闭了所有的资源。这是一个简单的事务管理实践,确保了在发生错误时数据的一致性。


需要注意的是:如果报错信息,没有捕获到SQLException 异常,或者报错信息并非SQLException 异常,事务回滚机制是不会触发的。所以其他的异常需要单独处理完,确保只捕获SQLException异常。 

赞 18