我正在为Java(使用Spring)的web应用程序的后端工作,并尝试使用构建器模式。我有类
- 示例(作为数据对象)
- ExampleDocument(作为另一个数据对象)
- ExampleMapper exampleerepository (extends MongoRepository)
- ExampleController (REST)
- ExampleService
现在我有一个函数返回一个可选的(findById, mongorepo)到我的服务的问题:
@Service
@RequiredArgsConstructor
public class ExampleService {
private final ExampleMapper exampleMapper;
private final ExampleRepository exampleRepository;
public Example getExample(String exampleId) {
Optional<ExampleDocument> document = exampleRepository.findById(exampleId);
return exampleMapper.mapToDto(document);
}
我想在我的mapper类中映射文档,就像我习惯对其他文档做的那样(没有Optional)它看起来是这样的,我从另一个类中取了一个例子:
@Component
public class OtherExampleMapper {
public OtherExample mapToDto(OtherExampleDocument document) {
return OtherExample.builder()
.id(document.getId())
.existingSolutions(document.getExistingSolutions())
...
.build();
}
)
我试图使用ifPresent,但builderPattern似乎不识别表达式,因为我在"getId()"上有一个黄色标记,告诉我"'PitchEventDocument.getId()'的结果被忽略了"。在".build()">
@Component
public class PitchEventMapper {
public Example mapToDto(Optional<ExampleDocument> document) {
return Example.builder()
.id(document.ifPresent(id -> document.get().getId())
.build();
}
如何将构建器模式与可选模式结合使用?
您的基本问题是ifPresent
根本不返回值-它是void
。相反,您需要orElse
(因为我认为在这种情况下您需要null
或其他默认值),并且不应该使用get
-所有相关的&;if&;和";or"方法已为您展开该值。
:
Example.builder()
.id(document.map(Document::getId).orElse(null))
.build()