我可以从服务返回dto和域实体吗?

pgx2nnw8  于 2021-07-14  发布在  Java
关注(0)|答案(0)|浏览(230)

我有一个spring-boot应用程序,我使用这样的dto:服务

@Service
public class UnitOfMeasureServiceImpl implements IUnitOfMeasureService {
private final IUnitsOfMeasureRepository unitOfMeasureRepository;

@Autowired
public UnitOfMeasureServiceImpl(IUnitsOfMeasureRepository unitOfMeasureRepository) {
    this.unitOfMeasureRepository = unitOfMeasureRepository;
}

@Override
public UnitOfMeasureDTO getUnitOfMeasureById(UUID id) {
    Optional<UnitOfMeasure> optionalUnitOfMeasure = unitOfMeasureRepository.findById(id);

    if (!optionalUnitOfMeasure.isPresent()){
        // throw new ComponentNotFoundException(id);
        return null;
    }
    return UnitOfMeasureDTO.factory(optionalUnitOfMeasure.get());

}

dto公司:

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UnitOfMeasureDTO {

    private String id;

    private String name;

    private String description;

    private String sourceInfoCompanyName;

    private String originalId;

    public static UnitOfMeasureDTO factory(UnitOfMeasure unitOfMeasure) {
            UnitOfMeasureDTO dto = new UnitOfMeasureDTO();

            dto.id = unitOfMeasure.getId().toString();
            dto.name = unitOfMeasure.getName();
            dto.description = unitOfMeasure.getDescription();
            dto.sourceInfoCompanyName = unitOfMeasure.getSourceInfo().getSourceCompany().getName();
            dto.originalId = unitOfMeasure.getOriginalId();
            return dto;
    }

  }

控制器:

@RestController
@RequestMapping(UnitOfMeasureController.BASE_URL)
public class UnitOfMeasureController {

public static final String BASE_URL = "/api/sust/v1/unitOfMeasures";

private final IUnitOfMeasureService unitOfMeasureService;

public UnitOfMeasureController(IUnitOfMeasureService unitOfMeasureService) {
    this.unitOfMeasureService = unitOfMeasureService;
}

@GetMapping(path = "/{id}")
@ResponseStatus(HttpStatus.OK)
public UnitOfMeasureDTO getUnitOfMeasureDTO(@PathVariable("id")  UUID id) {

    UnitOfMeasureDTO unitOfMeasureDTO = unitOfMeasureService.getUnitOfMeasureById(id);

    return unitOfMeasureDTO;
}

所以在我的服务中,我有getunitofmeasurebyid(uuid),它返回一个unitofmeasuredto。现在我需要从另一个服务调用getunitofmeasurebyid(uuid id),它返回域实体unitofmeasure。我认为从另一个服务调用服务方法是正确的(不是控制器方法!)业务逻辑之间的分离在服务层。那么,在服务中有两个方法:getunitofmeasuredtobyid和getunitofmeasurebyid正确吗(getunitofmeasuredtobyid调用getunitofmeasurebyid以避免代码重复)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题