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

Time:10-07

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\" : \"[email protected]\"}, Fields: {}, Sort: {} } returned non unique result.",
    "path": "/user"
}

What am I missing here?

CodePudding user response:

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);
                }

CodePudding user response:

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);   
}
  • Related