简体   繁体   中英

How save a list of users to database with foreach loop using java

I want to be able to send a list of users to my method, loop through each user and if user doesn't exist in database save it and if it exists throw an error.

I have this code so far:

public List<User> addUsers(@RequestBody List<User> userList) {
        List<User> newUserList = new ArrayList<>();
        userList.forEach(
                user -> {
                   userRepository.findByEmail(user.getEmail())
                           .orElseThrow(() -> new ResourceAlreadyExistsException("User with ", "email already exists.", user.getEmail()));
                    newUserList.add(user);
                }
        );
        return userRepository.saveAll(newUserList);   
    }

But I am getting this error:

{
    "timestamp": "2021-10-06T16:50:52.476+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Query { \"$java\" : Query: { \"email\" : \"domahaskins@gmail.com\"}, Fields: {}, Sort: {} } returned non unique result.",
    "path": "/user"
}

What am I missing here?

The logic used in the body of the loop is opposite on what you'd like to do.

                user -> {
                  // this will throw for any user whose email is not present in the DB
                   userRepository.findByEmail(user.getEmail())
                           .orElseThrow(() -> new ResourceAlreadyExistsException("User with ", "email already exists.", user.getEmail())); 

                    newUserList.add(user);
                }

Optional#orElseThrow

Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

In result of the above, newUserList will contain only users whose email is already present in the DB.

EDIT: Here's one solution for the task:

                user -> {
                   userRepository.findByEmail(user.getEmail())
                           .ifPresent(u -> {throw new ResourceAlreadyExistsException("User with ", "email already exists.", u.getEmail());});

                    newUserList.add(user);
                }

I have not tested but it can be this way.

In your repo change return Optional<Email> to Email or whatever Object you have. Or you can have method like boolean existsByEmail(String email)

// Email findByEmail(String email) or boolean existsByEmail(String email)

public List<User> addUsers(@RequestBody List<User> userList) {
        List<User> newUserList = new ArrayList<>();
        userList.forEach(
            user ->{
                    // if(userRepository.existsByEmail(user.getEmail())){
                    if(userRepository.findByEmail(user.getEmail())!=null){
                        new ResourceAlreadyExistsException("User with ", "email already exists.", user.getEmail())
                    }
                    newUserList.add(user);
                }
        );
        return userRepository.saveAll(newUserList);   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM