Search code examples
javaspringdesign-patternsservicedto

Service pattern store one to one with Dtos


I have a OperationService and a PostService, they handle some operations and business logic about operations and posts. On database level the operation has a one to one relationship to a post. What is the design approach to persists this? My services return only Dtos. And no concrete database entities. For example i persists a operation with a CreateOperationDto but in this there should only the id of the post. Than i have the postservice how return me a PostDto but i can not persists the PostDto directly. Hopefully can help someone.


Solution

  • It looks like you drew the boundaries between the services based on the data model rather than use cases. One option would be to change them and allow OperationService to save Posts (or even rename/ create a different service called CreateOperationSevice or CreateOperationUseCase for this purpose). If you find this approach interesting, take a look at this video.

    On the other hand, if you want to keep them decoupled like this, you can create a common facade that calls the 2 services in turn, inside the same transaction. something like this:

    @Component
    class OperationFacade {
        final OperationService operationService;
        final PostService postService;
    
        @Transactional
        public void createOperation(CreateOperationDto dto) {
            long operationId = operationService.save(dto.operation());
            postService.saveAll(dto.posts(), operationId);
        }
    }