spring简易版事务管理器实现

spring 事务简单实现

1 事务的四个条件ACID

  • 原子性(Atomicity):一个事务(transaction)中的所有操作,要么全部完成,要么全部不完成,不会结束在中间某个环节。事务在执行过程中发生错误,会被回滚(Rollback)到事务开始前的状态,就像这个事务从来没有执行过一样。
  • 一致性(Consistency):在事务开始之前和事务结束以后,数据库的完整性没有被破坏。这表示写入的资料必须完全符合所有的预设规则,这包含资料的精确度、串联性以及后续数据库可以自发性地完成预定的工作。
  • 隔离性(Isolation):数据库允许多个并发事务同时对其数据进行读写和修改的能力,隔离性可以防止多个事务并发执行时由于交叉执行而导致数据的不一致。事务隔离分为不同级别,包括读未提交(Read uncommitted)、读提交(read committed)、可重复读(repeatable read)和串行化(Serializable)。
  • 持久性 (Durability):事务处理结束后,对数据的修改就是永久的,即便系统故障也不会丢失。

2 代码实现

2.1 创建连接对象

@Component
public class ConnectionManager {

    @Autowired
    private DataSource dataSource;

    // 保证每个线程的connection是唯一的
    private ThreadLocal<Connection> connection = new ThreadLocal<>();

    public Connection getConnection() throws SQLException {
        if (connection.get() == null) {
            connection.set(dataSource.getConnection());
        }
        return connection.get();
    }
}

2.2 执行工具类

@Component
public class MyJdbcTemplate {

    @Autowired
    ConnectionManager connectionManager;

    public void execute(String sql) throws SQLException {
        Connection connection = connectionManager.getConnection();
        Statement statement = connection.createStatement();
        statement.execute(sql);
    }
}

2.3 业务代码

public class UserServiceTest {

        @Autowired
        MyJdbcTemplate jdbcTemplate;
    
        @MyTransactionl
        public void insert() throws SQLException {

            jdbcTemplate.execute("insert into sys_user VALUES(1,'eve',18)");

            jdbcTemplate.execute("INSERT into sys_log(id,operation) VALUES(1,'新增用户')");


        }
}

2.4 AOP增强实现事务

// 注解定义
public @interface MyTransactionl {
}
@Aspect
@Component
public class MyTransactionalAspect {

    @Autowired
    ConnectionManager connectionManager;

    @Around("@annotation(MyTransactionl)")
    public Object transactional(ProceedingJoinPoint point) throws Throwable {
        // 获取连接对象
        Connection connection = connectionManager.getConnection();
        connection.setAutoCommit(false);
        Object obj = null;
        try {
            // 执行业务代码
            obj = point.proceed();
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            connection.rollback();
        }finally {
            // 关闭连接对象
            connection.close();
        }
        return obj;
    }
}

一个基于注解的丐版事务实现完成,麻雀虽小,五脏俱全!

posted @ 2021-03-25 23:18  混吃等你  阅读(57)  评论(0编辑  收藏  举报