CRUD Repository findById() different return value

眉间皱痕 提交于 2019-12-08 09:51:00

问题


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 :(
    }
}

回答1:


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



回答2:


in your CrudRepo create a method:

Task getById(Integer id);

and then call this method in your TaskService and you should be ready to go:)



来源:https://stackoverflow.com/questions/49967316/crud-repository-findbyid-different-return-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!