spring-bootspring-mvc

How to perform update in Spring Boot application?


In a service UserServiceImpl.updateUser method I need to return Optional if repository userRepository.findById method returned Optional or perform update of selected entity. The code does not work:

import java.util.List;
import java.util.Optional;

@Data
public class CreateUpdateUserDto {
    String firstName;
    String lastName;
}

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String firstName;

    @Column
    private String lastName;

}
@RequiredArgsConstructor
@Service
public class UserServiceImpl implements UserService {

    private final ModelMapper modelMapper;

    private final UserRepository userRepository;

    public Optional<User> updateUser(long userId, CreateUpdateUserDto data) {
        // todo: need return Optional if optionalUser is true
        Optional<User> optionalUser = userRepository.findById(userId);
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            user.setFirstName(data.getFirstName());
            user.setLastName(data.getLastName());
            return userRepository.save(user);  <=== here error as at screenshot
        } else {
            return optionalUser;
        }
    }

}

The error:

enter image description here

How to perform update if repository returned an entity and in another case return Optional?


Solution

  • your "userRepository.save(user)" returns the actual User object and not the "Optional<User>". Wrap it with Optional to match your return type.

    return Optional.ofNullable(userRepository.save(user));