MrNVK
MrNVK

Reputation: 372

How to validate generic bean in REST service?

In my current project I frequently use bulk requests. I have simple BulkRequest<T> class:

import java.util.List;

import javax.validation.constraints.NotNull;

public class BulkRequest<T> {

    @NotNull private List<T> requests;

    public List<T> getRequests() { return this.requests; }

    public void setRequests(List<T> requests) { this.requests = requests; }
}

It very simple to use with other beans, for example:

@RequestMapping(value = "/departments/{departmentId}/patterns",
                method = RequestMethod.POST,
                produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> post(
  final @PathVariable long departmentId,
  final @Valid @RequestBody BulkRequest<AddPatternRequest> bulkRequest
) {
  ...
}

AddPatternRequest contains own rules for validation and represents only one request, which can be collected to bulk request:

import javax.validation.constraints.NotNull;

public class AddPatternRequest {

  @NotNull private Long pattern;

  public Long getPattern() { return this.pattern; }

  public void setPattern(Long pattern) { this.pattern = pattern; }
}

But there's a problem. After the controller receives the bulk request, it validates only BulkRequest and checks if requests collection is null or not, but I need to validate nested request too.

How can I do it?

Upvotes: 0

Views: 1420

Answers (1)

StanislavL
StanislavL

Reputation: 57381

Add @Valid to the requests. Like this

@NotNull 
@Valid
private List<T> requests;

Then nested objects are also validated

Upvotes: 5

Related Questions