java CRUD Repository findById() 不同的返回值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49967316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:30:00  来源:igfitidea点击:

CRUD Repository findById() different return value

javaspringcrud

提问by ehr

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

在我的 SpringBoot 应用程序中,我使用的是 CrudRepo。我发现返回值有问题:Required != Found

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

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.

无论将方法返回类型从 Task 更改为 Object -> IDE 停止显示错误,但由于稍后验证数据类型可能会出现问题。

Do you know how to fix it? Any hint?

你知道如何解决吗?任何提示?

CrudRepo

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

回答by buddha

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:

findById 方法是 return 可选的,因此您可以通过 get() 方法获取任务。您可以选择以下3种情况您将在找不到任务时出现异常:

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

回答by Joginder Malik

I think no need to create getById(... id) method in Repository bean class because in SimpleJPARepository such method is already implemented. So you can directly call this method. See Official spring document:-

我认为不需要在 Repository bean 类中创建 getById(... id) 方法,因为在 SimpleJPARepository 中已经实现了这样的方法。所以可以直接调用这个方法。请参阅官方春季文件:-

/*
     * (non-Javadoc)
     * @see org.springframework.data.repository.CrudRepository#findById(java.io.Serializable)
     */
    public Optional<T> findById(ID id) {

        Assert.notNull(id, ID_MUST_NOT_BE_NULL);

        Class<T> domainType = getDomainClass();

        if (metadata == null) {
            return Optional.ofNullable(em.find(domainType, id));
        }

        LockModeType type = metadata.getLockModeType();

        Map<String, Object> hints = getQueryHints().withFetchGraphs(em).asMap();

        return Optional.ofNullable(type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints));
    }

回答by nirfrea

in your CrudRepo create a method:

在您的 CrudRepo 中创建一个方法:

Task getById(Integer id);

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

然后在你的 TaskService 中调用这个方法,你应该准备好了:)