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!

我认为这很有意义,但是当我开始进一步调试时,发现了这一点:

enter image description here

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

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

解决方法

也许您可以调整存储库实现以将实体返回为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())