gpt4 book ai didi

mysql - 在 spring 中,如何在一次迭代发生事务回滚后继续来自 Controller for 循环的请求

转载 作者:行者123 更新时间:2023-11-29 17:04:21 25 4
gpt4 key购买 nike

在服务层发生任何回滚后请求将关闭。它不会从 Controller 继续。

例如:

public Class UserController {
@Autowired
UserService userService;
createUserList(List < User > list) {
try {
RespObj obj=new RespObj();
List < Obj > errorList = new ArrayList();
for (User user: list) {
Object obj = userService.createUser(user);
errorList.add(obj);
}
//return success response along with any errorlist
obj.setStatus(200);
obj.setObj(errorList);
return obj;
} catch (Exception e) {
//returning error response
obj.setStatus(400);
obj.setObj(e.getMessage());
return obj;
}
}
}

//UserServiceImpl

public class UserServiceImpl implements UserService {
@Transactional
Object createUser(user) {
try {
dao.saveUser(user);
} catch (Exception e) {
//create error pojo
}
// return error pojo if any
}
}

在上面的代码中,如果任何一个用户创建失败,则仅对该用户进行回滚,之后不再处理剩余的用户对象。

要求是:留下失败的用户对象,并需要处理剩余未处理的用户对象。

最佳答案

像这样更新您的代码以处理所有用户,将错误添加到 errorList。

RespObj obj=new RespObj();
List < Obj > errorList = new ArrayList();
for (User user: list) {
User user = new Object;
try {
user = userService.createUser(user);
} catch (Exception e) {
obj.setMessage(e.getMessage());
obj.setStatus(400);
errorList.add(obj);
}
}
obj.setStatus(200);
obj.setErrorList(errorList);
return obj;
}

关于mysql - 在 spring 中,如何在一次迭代发生事务回滚后继续来自 Controller for 循环的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com