0

I have added annotations in the parent class. It is working fine.

But it is not working in the member variables that is declared as another Object type. It is validating:

  • orderId from base class
  • referenceNumber from MarchantApplicationRequest
  • @NotEmpty annotation at customerRequests field in MerchantApplicationRequest.

But it is not validating customerRoleType in CustomerRequest.

Also, I would like to add @NotBlank annotation in customerRequests. But it is not taking this, though it is taking @NotEmpty annotation.

Class MerchantApplicationRequest

@JsonIngnoreProperties(ignoreUnknown=false) 
public class  MerchantApplicationRequest extends IomBaseDTO {
    @NotEmpty(message="customerRequests is mandatory")
    private List<CustomerRequest> customerRequests;
    @NotBlank(message="referenceNumber is mandatory")
    private String referenceNumber ;
}

Class CustomerRequest

public class  CustomerRequest  { 
    @NotBlank(message="customerRoleType is mandatory")
    private String customerRoleType ;
}

Controller class

Method where to apply validation:

    @PostMapping("/orderDetail")
    public void orderDetail(@Valid @RequestBody MerchantApplicationRequest request) {
       
        try {
            iOrderService.updateProductDetail(request);
        } catch (Exception e) {
            // ...
        }
    }

Here is my JSON payload:

    {
       "orderId" : 101,
       "referenceNumber" : "123",
       "customerRequests" : [ {
         "customerRoleType" : null
       }]
    }

I am using in pom.xml of Spring Boot application:

<dependency> 
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>
user1634050
  • 25
  • 1
  • 7

2 Answers2

1

If you want to cascade the validation you have to add the @Valid annotation:

@Valid
@NotEmpty(message="customerRequests is mandatory")
private List<CustomerRequest> customerRequests;

Please read more about cascading in the Hibernate Validation documentation: Example 2.11: Cascaded validation

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
0

Using bean-validation (javax.validation), you can add validation to elements of collections.

Using Bean-Validation 1.0

@JsonIngnoreProperties(ignoreUnknown=false) 
public class  MerchantApplicationRequest extends IomBaseDTO {

    @NotEmpty(message="customerRequests is mandatory")
    @Valid
    private List<CustomerRequest> customerRequests;

    @NotBlank(message="referenceNumber is mandatory")
    private String referenceNumber ;
}

See also:

Alternative since Bean-Validation 2.0

In Java 8 generic types can also be validated by prepending the annotation before the type inside the diamond-operator, e.g. <@Valid CustomerRequest>. This is a more concise way of defining per-element validation. It has the same effect like the traditional way, validates every given element as defined in the class (CustomerRequest).

See also:

hc_dev
  • 8,389
  • 1
  • 26
  • 38