【发布时间】:2019-03-18 07:51:14
【问题描述】:
设置父实体的最佳位置在哪里?换句话说,将实体放在一起的最佳位置在哪里?
在控制器中,找到父实体并设置为子实体然后保存?
@RestController
public class SomeController{
@Autowired
private SomeService someService;
@PostMapping("/parents/{parentEntityId}/childs")
public ResponseEntity<Void> save(@PathVariable("parentEntityId") Long parentEntityId, @RequestBody ChildDto childDto) {
Optional<ParentEntity> parentEntity = someService.findParentById(parentEntityId);
if (parentEntity.isPresent()) {
ChildEntity childEntity = childDtoMapper.fromDto(childDto);
childEntity.setParent(parentEntity.get());
someService.saveChild(childEntity);
return ResponseEntity.created(...).build();
}
throw new EntityNotFoundException("Parent entity not found!");
}
}
或
在控制器中,将 dto 映射到实体,然后将实体和父实体 id 发送到服务,然后通过 id 找到父实体并设置为子实体并保存?
@RestController
public class SomeController {
@Autowired
private SomeService someService;
@PostMapping("/parents/{parentEntityId}/childs")
public ResponseEntity<Void> save(@PathVariable("parentEntityId") Long parentEntityId, @RequestBody ChildDto childDto) {
ChildEntity childEntity = childDtoMapper.fromDto(childDto);
someService.saveChild(parentEntityId, childEntity);
return ResponseEntity.created(...).build();
}
}
public class SomeServiceImpl {
@Autowired
private ParentEntityRepository parentEntityRepository;
@Autowired
private ChildEntityRepository childEntityRepository;
public ChildEntity saveChild(final long parentEntityId, final ChildEntity childEntity){
Optional<ParentEntity> parentEntity = parentEntityRepository.findById(parentEntityId);
if (parentEntity.isPresent()) {
childEntity.setParent(parentEntity.get());
childEntityRepository.save(childEntity);
return childEntity;
}
throw new EntityNotFoundException("Parent entity not found!");
}
}
【问题讨论】:
标签: java spring rest spring-mvc