我尝试在DB中一次性插入一些记录,也尝试了for循环,但从未发生,如果我保存单个记录,它工作
@RequiredArgsConstructor
@Service
public class UserServiceImpl {
private final UserRepository userRepo;
private final FamilyRepository familyRepo;
public Mono<ServerResponse> insertUserData(ServerRequest serverRequest) {
return serverRequest.bodyToMono(UserAndFamilyRequest.class)
// .map(userAndFamilyRequest -> {
// List<FamilyMember> list = userAndFamilyRequest.getFamilyMemberList();
// list.stream().forEach((familyMember) ->
// {
// System.out.println(familyMember.getName());
// FamilyMemberEntity familyMemberEntity = new FamilyMemberEntity();
// familyMemberEntity.setAge(familyMember.getAge());
// familyMemberEntity.setName(familyMember.getName());
// familyRepo.save(familyMemberEntity);//doesn't work either
// try{
// Thread.sleep(2000);
// }catch(Exception ex){
//
// }
//
// });
// return userAndFamilyRequest;
// })
.map(userAndFamilyRequest -> {
List<FamilyMember> list = userAndFamilyRequest.getFamilyMemberList();
var entityList = list.stream().map(familyMember -> {
FamilyMemberEntity familyMemberEntity = new FamilyMemberEntity();
familyMemberEntity.setName(familyMember.getName());
familyMemberEntity.setAge(familyMember.getAge());
return familyMemberEntity;
}).collect(Collectors.toList());
familyRepo.saveAll(entityList);//doesn't work
return userAndFamilyRequest;
})
.flatMap(userAndFamilyRequest -> {
UserEntity userEntity = new UserEntity();
User user = userAndFamilyRequest.getUser();
userEntity.setSeats(userAndFamilyRequest.getFamilyMemberList().size());
userEntity.setAge(user.getAge());
userEntity.setName(user.getName());
return userRepo.save(userEntity);
})
// .flatMap(userAndFamilyRequest -> {
// FamilyMember familyMember = userAndFamilyRequest.getFamilyMemberList().get(0);
// FamilyMemberEntity familyMemberEntity = new FamilyMemberEntity();
// familyMemberEntity.setAge(familyMember.getAge());
// familyMemberEntity.setName(familyMember.getName());
// return familyRepo.save(familyMemberEntity);//single save works
// })
.flatMap(userEntity -> ServerResponse.created(URI.create("users"+userEntity.getId()))
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(userEntity));
}
}
控制台中无错误
2条答案
按热度按时间yquaqz181#
在保存数据函数中添加try {} catch,这样就可以知道遇到了什么错误
but5z9lq2#
嗯,我自己找到了答案,familyRepo.save内部Map不会自己工作,因为它返回一个只有在订阅时才会执行的通量,用flatMap(自动订阅)替换它解决了这个问题。