title: Validation in DDD with Spring
body: <p>I will build a new application with DDD in Spring. I will have a REST adapter, a JPA adapter and my domain model.</p>
  <p>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?</p>
  <p>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.</p>
  <p>But is this the right way to do it in DDD?</p>
  <p>When I do the validation in my domain, I am still a little bit confused. I need the validation errors in my REST response.</p>
  <p>If I have this RestController:</p>
  <pre><code>  @RequestMapping(
        method = RequestMethod.POST,
        path = &quot;/orders&quot;,
        consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity&lt;String&gt; addOrder(@RequestBody orderDTO orderDTO) {
      Order order = ... // map to domain opject
      Set&lt;ConstraintViolation&lt;Order&gt;&gt; violations = orderService.validate(order);
      if(violations.isEmpty()) {
        orderService.save(order);
        return ResponseEntity.ok().build();
      } else {
        return ResponseEntity.badRequest().build();
      }
    }
  </code></pre>
  <p>And a domain service like this:</p>
  <pre><code>public class OrderServiceImpl implements OrderService {
  
    public Set&lt;ConstraintViolation&lt;Order&gt;&gt; validate(Order order) {
      ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
      Validator validator = factory.getValidator();
      Set&lt;ConstraintViolation&lt;Order&gt;&gt; violations = validator.validate(order);
      return violations;
    }
  
    public void save(Order order) {
      orderRepository.save(order);
    }
  }
  </code></pre>
  <p>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.</p>