CRUD存储库findById()不同的返回值 [英] CRUD Repository findById() different return value

查看:407
本文介绍了CRUD存储库findById()不同的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SpringBoot应用程序中,我正在使用CrudRepo。
我发现返回值有问题:必填!=找到

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

无论将方法返回类型从任务更改为对象-> IDE都停止显示错误,但是由于稍后要验证数据类型,这可能是问题。

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.

你知道怎么解决吗?

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


推荐答案

findById方法返回Optional,因此可以通过get()方法获取任务。可以选择以下3种情况
当找不到Task时会出现异常: p>

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

找不到任务时,您将得到null:

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

或仅返回可选对象

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

这篇关于CRUD存储库findById()不同的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆