【问题标题】:How can take value request DTOs in my service @PutMapping如何在我的服务@PutMapping 中获取价值请求 DTO
【发布时间】:2021-11-07 13:48:12
【问题描述】:

我正在尝试执行@PutMapping,我将在其中放置所有逻辑来更改服务中的属性,但我遇到了问题。如何从我的 requestDTO 中获取值以在类中播放并在服务中而不是在控制器中进行这些更改?

请求数据与响应和类相同

private Long id;


private String program;

我的控制器和服务实现

 @PutMapping(value = "/edit-program/test/{id}")
    public ResponseEntity<ProgramResponseDto> updateProgramByIdTest (
            @PathVariable(value = "id") final Long id,
            @Valid @RequestBody final ProgramRequestDto programRequestDto) throws UpdateDataException {

        ProgramResponseDto programResponseDto = ProgramMapper.INSTANCE.programToProgramResponseDTO(
                programService.Update(id));

        log.info(LocaleContext.format("response.success",
                (new Object() {
                }.getClass().getEnclosingMethod().getName()),
                HttpStatus.OK.toString()));

                return status(HttpStatus.OK).body(programResponseDto);

    }

  @Override
    public Program Update(Long id) throws UpdateDataException {

    Program program = null;

    try {

        Optional<Program> programDB = programRepository.findById(id);

        if (programDB.isPresent()) {

            program = programDB.get();

            ProgramRequestDto programRequestDto = ProgramRequestDto.builder().build();
            program.setProgram(programRequestDto.getProgram());
            program.setId(programRequestDto.getId());

            return programRepository.save(program);
        }
    } catch (Exception e){
        throw new UpdateDataException(e.getMessage());

    }
    return null;
}

服务 程序更新(长id)抛出UpdateDataException;

【问题讨论】:

  • 将 dto 向下传递。
  • 只需将 dto 传递给 Update 方法,然后将服务注入您的控制器,然后从您的服务中调用 Update 方法。
  • 非常感谢,我真的没有意识到,当我通过dto时,我可以拿起它并使用它。谢谢

标签: java spring-boot rest spring-data-jpa crud


【解决方案1】:

将Service方法的签名改为接受ProgramRequestDto如下:

public Program Update(ProgramRequestDto programRequestDto) throws UpdateDataException

并相应地更新控制器:

@PutMapping(value = "/edit-program/test/{id}")
public ResponseEntity<ProgramResponseDto> updateProgramByIdTest (
         @PathVariable(value = "id") final Long id,
         @Valid @RequestBody final ProgramRequestDto programRequestDto) throws UpdateDataException {

     ProgramResponseDto programResponseDto = ProgramMapper.INSTANCE.programToProgramResponseDTO(
             programService.Update(programRequestDto));

     log.info(LocaleContext.format("response.success",
             (new Object() {}.getClass().getEnclosingMethod().getName()),
             HttpStatus.OK.toString()));

     return status(HttpStatus.OK).body(programResponseDto);
}

不确定这是否是您想要的,但这是我从您的问题中理解的。

【讨论】:

  • 非常感谢 João,我无法这样看待它,而这正是我想做的。非常感谢您的澄清
猜你喜欢
  • 2020-02-10
  • 2013-11-26
  • 2011-07-26
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 2023-03-23
相关资源
最近更新 更多