Home > Blockchain >  Validation in DDD with Spring
Validation in DDD with Spring

Time:11-25

I will build a new application with DDD in Spring. I will have a REST adapter, a JPA adapter and my domain model.

My question is where to do the field validation? Let's say I have a REST method to place an order, where should I validate that the order quantity in the request is greater than 0? In the DTO of the REST adapter? Or in my domain entity, because the validation should be part of the business logic?

If I do the validation in the DTO of the REST request I just can add the validation checks to the fields of the DTO and validate it with the @Valid annotation in my REST controller. And in this case the controller will return the validation errors directly to the client.

But is this the right way to do it in DDD?

CodePudding user response:

Definitely the domain model, probably both.

Firstly, in the Domain Model. The quantity check is a business rule so this invariant should be guarded by the domain entity. This means that your domain entities are ensuring that all invariants are enforced. Your domain entities should never let themselves be created (or updated) in an invalid state.

Secondly, if you want optimal experience for the user you could implement additional validations (using annotations or otherwise) on the DTO models themselves.

CodePudding user response:

Thanks. But I am still a little bit confused. I need the validation errors in my REST response.

If I have this RestController:

  @RequestMapping(
      method = RequestMethod.POST,
      path = "/orders",
      consumes = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<String> addOrder(@RequestBody orderDTO orderDTO) {
    Order order = ... // map to domain opject
    Set<ConstraintViolation<Order>> violations = orderService.validate(order);
    if(violations.isEmpty()) {
      orderService.save(order);
      return ResponseEntity.ok().build();
    } else {
      return ResponseEntity.badRequest().build();
    }
  }

And a domain service like this:

public class OrderServiceImpl implements OrderService {

  public Set<ConstraintViolation<Order>> validate(Order order) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Order>> violations = validator.validate(order);
    return violations;
  }

  public void save(Order order) {
    orderRepository.save(order);
  }
}

What is the best way to get the validation errors as a JSON payload in the response? Is this the right way? I could not find any good example for the validation in the domain service and send the validation errors back to the client in the response.

  • Related