Warm tip: This article is reproduced from stackoverflow.com, please click
crud java spring

CRUD Repository findById() different return value

发布于 2020-04-23 13:47:22

In my SpringBoot applicatication I'm using CrudRepo. I have found a problem with return value: Required != Found

GitHub: https://github.com/einhar/WebTaskManager/tree/findById-problem

No matter about changing method return type from Task into Object -> IDE stopped show error, but then it could be problem due to validation of data type later on.

Do you know how to fix it? Any hint?

CrudRepo

public interface TaskRepository extends CrudRepository<Task, Integer> {}

Service

@Service
@Transactional
public class TaskService {

    @Autowired
    private final TaskRepository taskRepository;

    public TaskService(TaskRepository taskRepository) {
        this.taskRepository = taskRepository;
    }

    public List<Task> findAll() {
        List<Task> tasks = new ArrayList<>();
        for (Task task : taskRepository.findAll()) {
                tasks.add(task);
        }
        return tasks; // Work properly :)
    }
    /* ... */
    public Task findTask(Integer id) {
        return taskRepository.findById(id); // Find:Task | Required: java.util.Optional :(
    }
}
Questioner
ehr
Viewed
32
buddha 2018-04-22 23:48

The findById method is return Optional, So you can get the task by get() method. You can choose the following 3 case You will get an exception when Task not found:

public Task findTask(Integer id) {
    return taskRepository.findById(id).get();
}

You will get null when Task not found:

public Task findTask(Integer id) {
    return taskRepository.findById(id).orElse(null);
}

You will get an empty new Task when Task not found:

public Task findTask(Integer id) {
    return taskRepository.findById(id).orElse(new Task());
}

Or just return the Optional Object

public Optional<Task> findTask(Integer id) {
    return taskRepository.findById(id);
}