首页 > 解决方案 > Java - DTO 接口 target.targetSource 值 null ->“某些值”

问题描述

我正在使用 DTO 接口从自定义 Spring/Boot Repository 方法中获取数据。然后使用 DTO 拾取一个真实的实体。为了进一步解释,这是我的实现:

public interface ModuleEntityDTO {
    Long getId();
    String getReference();
    String getModuleName();
}
@Repository
public interface ModuleRepository extends CrudRepository<ModuleEntity, Long> {

    @Query("SELECT U.id, U.moduleName, U.reference FROM ModuleEntity as U WHERE U.reference = :reference")
    ModuleEntityDTO getByReference(@Param("reference") String reference);
}

调用该getByReference方法后,我使用返回的 DTO 来获取实体的真实实现,然后将其传递给 Student 对象并保存到其中:

ModuleEntityDTO moduleEntity = this.moduleRepository.getByReference(module.getReference().toString());
Optional<ModuleEntity> fullModule = this.moduleRepository.findById(moduleEntity.getId());

if(fullModule.isPresent()) {
        targetEntity.setModules(fullModule.get());
        this.timeTableRepository.save(targetEntity);
    } else {
        throw new Exception(ErrorMessages.CANNOT_FIND_MODULE(module.getReference()));
    }
}

这就是事情变得奇怪的地方。此调用Optional<ModuleEntity> fullModule = this.moduleRepository.findById(moduleEntity.getId());失败并返回错误:The given id must not be null!; nested exception is java.lang.IllegalArgumentException: The given id must not be null!

我认为这是有道理的,但是当我开始进一步调试时,我发现了这一点:

在此处输入图像描述

所以我们有null -> "some value"

这是什么意思?它是空的吗?它不为空吗?运行时说 null 但调试器说 null 和 value。我将如何获得这个价值?有人还可以解释这里发生了什么吗?

标签: javaspring-bootinterfacedto

解决方案


也许您可以调整存储库实现以将实体作为Optional值返回。在服务层,空值评估和 DTO 转换可以与结果一起完成。

Optional<ModuleEntity> module = moduleRepository.getByReference(id);

ModuleEntityDTO moduleEntity = module.map(moduleMapper::toDto).orElseThrow(() -> new ResourceNotFoundException(id, "Module not found"));

Optional<ModuleEntity> fullModule = this.moduleRepository.findById(moduleEntity.getId())

推荐阅读