综合案例-课程表批量新增加事务管理

1.service层

  • 接口
  1. /*
  2. 批量添加
  3. */
  4. void batchAdd(List<User> users);
  • 实现类
  1. /*
  2. 事务要控制在此处
  3. */
  4. @Override
  5. public void batchAdd(List<User> users) {
  6. //获取数据库连接
  7. Connection connection = JDBCUtils.getConnection();
  8. try {
  9. //开启事务
  10. connection.setAutoCommit(false);
  11. for (User user : users) {
  12. //1.创建ID,并把UUID中的-替换
  13. String uid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
  14. //2.给user的uid赋值
  15. user.setUid(uid);
  16. //3.生成员工编号
  17. user.setUcode(uid);
  18. //模拟异常
  19. //int n = 1 / 0;
  20. //4.保存
  21. userDao.save(connection,user);
  22. }
  23. //提交事务
  24. connection.commit();
  25. }catch (Exception e){
  26. try {
  27. //回滚事务
  28. connection.rollback();
  29. }catch (Exception ex){
  30. ex.printStackTrace();
  31. }
  32. e.printStackTrace();
  33. }finally {
  34. JDBCUtils.close(connection,null,null);
  35. }
  36. }

2.dao层

  • 接口
  1. /**
  2. 支持事务的添加
  3. */
  4. void save(Connection connection,User user);
  • 实现类
  1. /*
  2. 支持事务的添加
  3. */
  4. @Override
  5. public void save(Connection connection, User user) {
  6. //定义必要信息
  7. PreparedStatement pstm = null;
  8. try {
  9. //1.获取连接
  10. connection = JDBCUtils.getConnection();
  11. //2.获取操作对象
  12. pstm = connection.prepareStatement("insert into user(uid,ucode,loginname,password,username,gender,birthday,dutydate)values(?,?,?,?,?,?,?,?)");
  13. //3.设置参数
  14. pstm.setString(1,user.getUid());
  15. pstm.setString(2,user.getUcode());
  16. pstm.setString(3,user.getLoginname());
  17. pstm.setString(4,user.getPassword());
  18. pstm.setString(5,user.getUsername());
  19. pstm.setString(6,user.getGender());
  20. pstm.setDate(7,new Date(user.getBirthday().getTime()));
  21. pstm.setDate(8,new Date(user.getDutydate().getTime()));
  22. //4.执行sql语句,获取结果集
  23. pstm.executeUpdate();
  24. }catch (Exception e){
  25. throw new RuntimeException(e);
  26. }finally {
  27. JDBCUtils.close(null,pstm,null);
  28. }
  29. }