title: Spring Boot: Optional mapping of request parameters to POJO
body: <p>I'm trying to map request parameters of a controller method into a POJO object, but only if any of its fields are present. However, I can't seem to find a way to achieve this. I have the following POJO:</p>
  <pre class="lang-java prettyprint-override"><code>public class TimeWindowModel {
  
      @NotNull
      public Date from;
  
      @NotNull
      public Date to;
  
  }
  </code></pre>
  <p>If none of the fields are specified, I'd like to get an empty <code>Optional</code>, otherwise I'd get an <code>Optional</code> with a validated instance of the POJO. Spring supports mapping request parameter into POJO objects by leaving them unannotated in the handler:</p>
  <pre class="lang-java prettyprint-override"><code>@GetMapping(&quot;/shop/{shopId}/slot&quot;)
  public Slice&lt;Slot&gt; getSlots(@RequestAttribute(&quot;staff&quot;) Staff staff,
                              @PathVariable(&quot;shopId&quot;) Long shopId, @Valid TimeWindowModel timeWindow) {
      // controller code
  }
  </code></pre>
  <p>With this, Spring will map request parameters &quot;from&quot; and &quot;to&quot; to an instance of TimeWindowModel. However, I want to make this mapping optional. For POST requests you can use <code>@RequestBody @Valid Optional&lt;T&gt;</code>, which will give you an <code>Optional&lt;T&gt;</code> containing an instance of T, but only if a request body was provided, otherwise it will be empty. This makes <code>@Valid</code> work as expected.</p>
  <p>When not annotated, <code>Optional&lt;T&gt;</code> doesn't appear to do anything. You always get an <code>Optional&lt;T&gt;</code> with an instance of the POJO. This is problematic when combined with <code>@Valid</code> because it will complain that &quot;from&quot; and &quot;to&quot; are not set.</p>
  <p>The goal is to get either (a) an instance of the POJO where <em>both</em> &quot;from&quot; and &quot;to&quot; are not null or (b) nothing at all. If only one of them is specified, then <code>@Valid</code> should fail and report that the other is missing.</p>