java - 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。我将如何获得这个价值?有人还可以解释这里发生了什么吗?
解决方案
也许您可以调整存储库实现以将实体作为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())
推荐阅读
- mysql - 我想使用 mysql 在 2 列中获取元素
- ios - 使用使用 MLKit 的框架时缺少必需的模块“MLKit”错误
- php - 没有@php指令的Laravel Blade模板分配变量?
- python - 根据时间列计算日期列中的值
- spring-webflux - 不使用 EmitProcessor 的非阻塞锁
- mysql - 在 mysql 中查找匹配对的 sql 查询
- excel - Excel - 如何对 LEFT 的结果求和?
- amazon-web-services - lamda 处理未触发的 SQS 消息
- node.js - 如何使护照会话接受其他输入
- python - 使用正则表达式从文本文件中打印内容