I want to validate my object from csv file based on my DTO CustomerFailedPaymentDto object before i process it. I use @Valid but still is not working.
Mycontroller.java
@PostMapping("/proccessFile")
public String proccessFile(@RequestParam("file") MultipartFile file) {
// parse CSV file to create a list of `User` objects
try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
// create csv bean reader
CsvToBean<CustomerFailedPaymentDto> csvToBean = new CsvToBeanBuilder(reader)
.withType(CustomerFailedPaymentDto.class)
.withIgnoreLeadingWhiteSpace(true)
.build();
// I WANT TO VALIDATE THIS OBJECT
List <@Valid CustomerFailedPaymentDto> customerFailedPayment = csvToBean.parse();
return virtualAccountService.buildFailedQuery(customerFailedPayment);
} catch (Exception ex) {
return "An error occurred while processing the CSV file.";
}
}
CustomerFailedPaymentDto.java
@Data
public class CustomerFailedPaymentDto {
private Long id;
@NotEmpty(message = "Please provide a bankPartner")
private String bankPartner;
@NotEmpty(message = "Please provide a bankCoreCode")
private String bankCoreCode;
@NotEmpty(message = "Please provide a transactionDate")
private String transactionDate;
}
How to ensure that object i get from csv file is valid based on my DTO class validation?
The validation needs to be triggered, in your case spring doesn't do it.
Use javax.validation.Validator
Autowired Validator first
@Autowired
private final Validator validator;
Then for each list item validate using the validator.
Set<ConstraintViolation<CustomerFailedPaymentDto>> violations = validator.validate(perCustomerFailedPayment);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(violations));
}