Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CRUD Repository findById() different return value

Tags:

java

spring

crud

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 :(
    }
}
like image 874
ehr Avatar asked Oct 15 '25 23:10

ehr


1 Answers

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);
}
like image 121
buddha Avatar answered Oct 18 '25 13:10

buddha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!