Search code examples
javaspringspring-bootoption-typedto

How to make return type nullable using Optional<T> etc?


I have the following method that returns DemoDTO and if it is not found, return exception.

public DemoDTO findShallowByUuid(UUID uuid) {
    return demoRepository.findShallowByUuid(uuid)
            .orElseThrow(() -> new EntityNotFoundException("Not found"));
}

However, I want to let the method to return a nullable DemoDTO instead of throwing error. For this purpose, I converted its type and the related return types to Optional<DemoDTO> or Optional<T>, but it caused some problems regarding to the related DTO. After I updated the constructor parameters to Optional<T>, the other part of the app that using this DTO complained.

I am not sure converting to Optional<T> is a good idea or not. If it is a good idea, should I add another constructor to the DemoDTO? I am not sure if it is a good solution as it will also require some changes for the property types. Any idea?


Solution

  • To put my comment into an answer, this would be the most elegant way based on your requirements:

    public DemoDTO findShallowByUuid(UUID uuid) {
        return demoRepository.findShallowByUuid(uuid).orElse(null);
    }
    

    But be sure that the calling code correctly handles null to avoid NullPointerExceptions.