综合-课程表批量新增加事务管理
# 综合-课程表批量新增加事务管理
事务控制在service层,而不是dao层,dao是一些共性的,应该交付给service处理,事务一般就是批量更改、添加等操作,检测用户提交的信息是否合法,否则 无法进入dao层,回滚到上一级,无法添加到数据库。
# 1.service层
- 接口
/*
批量添加
*/
void batchAdd(List<User> users);
1
2
3
4
2
3
4
- 实现类
/*
事务要控制在此处
*/
@Override
public void batchAdd(List<User> users) {
//获取数据库连接
Connection connection = JDBCUtils.getConnection();
try {
//开启事务
connection.setAutoCommit(false);
for (User user : users) {
//1.创建ID,并把UUID中的-替换
String uid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
//2.给user的uid赋值
user.setUid(uid);
//3.生成员工编号
user.setUcode(uid);
//模拟异常
//int n = 1 / 0;
//4.保存
userDao.save(connection,user);
}
//提交事务
connection.commit();
}catch (Exception e){
try {
//回滚事务
connection.rollback();
}catch (Exception ex){
ex.printStackTrace();
}
e.printStackTrace();
}finally {
JDBCUtils.close(connection,null,null);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 2.dao层
- 接口
/**
支持事务的添加
*/
void save(Connection connection,User user);
1
2
3
4
2
3
4
- 实现类
/*
支持事务的添加
*/
@Override
public void save(Connection connection, User user) {
//定义必要信息
PreparedStatement pstm = null;
try {
//1.获取连接
connection = JDBCUtils.getConnection();
//2.获取操作对象
pstm = connection.prepareStatement("insert into user(uid,ucode,loginname,password,username,gender,birthday,dutydate)values(?,?,?,?,?,?,?,?)");
//3.设置参数
pstm.setString(1,user.getUid());
pstm.setString(2,user.getUcode());
pstm.setString(3,user.getLoginname());
pstm.setString(4,user.getPassword());
pstm.setString(5,user.getUsername());
pstm.setString(6,user.getGender());
pstm.setDate(7,new Date(user.getBirthday().getTime()));
pstm.setDate(8,new Date(user.getDutydate().getTime()));
//4.执行sql语句,获取结果集
pstm.executeUpdate();
}catch (Exception e){
throw new RuntimeException(e);
}finally {
JDBCUtils.close(null,pstm,null);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
上次更新: 2023/09/05 17:45:42