如何解决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"
这是什么意思?它为空吗?它不为空吗?运行时说空,但调试器说空和值。我将如何获得这个价值?有人还能解释一下这里发生了什么吗?
解决方法
也许您可以调整存储库实现以将实体返回为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())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。