综合案例-课程表批量新增加事务管理
1.service层
/*
批量添加
*/
void batchAdd(List<User> users);
/*
事务要控制在此处
*/
@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);
}
}
2.dao层
/**
支持事务的添加
*/
void save(Connection connection,User user);
/*
支持事务的添加
*/
@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);
}
}