'How to perform Data Type validations for each individual fields of a POJO in Java?
I have a Request POJO class which comes with all String data type fields. When I have to store them to DB, the data types must be accurate. Considering that I need to validate and convert my each individual POJO fields to the respective data types. Also, Request POJO might consists of more than 200 fields. How can I validate and convert each of my field? This is what my Request POJO Looks like ->
@Data
public class ProductRequest {
private String goodScore;
private String invalidScore;
private String income;
private String salary;
private String updatedOn;
}
This is my Response POJO should look like, these are the types I actually need to store in DB ->
@Builder
@Data
public class ProductResponse {
private Integer goodScore;
private Integer invalidScore;
private Float income;
private Double salary;
private LocalDate updatedOn;
}
And this is how I have tried and implemented ->
public class ProductImplement {
public static void main(String[] args) {
ProductRequest request = new ProductRequest();
try {
ProductResponse.builder()
.goodScore(!StringUtils.hasLength(request.getGoodScore()) ? Integer.parseInt(request.getGoodScore())
: null)
.income(!StringUtils.hasLength(request.getIncome()) ? Float.parseFloat(request.getIncome()) : null)
.invalidScore(
!StringUtils.hasLength(request.getInvalidScore()) ? Integer.parseInt(request.getInvalidScore())
: null)
.salary(!StringUtils.hasLength(request.getSalary()) ? Double.parseDouble(request.getSalary()) : null)
.updatedOn(
!StringUtils.hasLength(request.getUpdatedOn()) ? LocalDate.parse(request.getUpdatedOn()) : null)
.build();
}catch(Exception e) {
e.printStackTrace();
}
}
}
So, if the value is not Null I parse the type and set. Otherwise I set the field value to Null. But, in this case if any exception occurs while parsing, the whole object returns Null and it is hectic to do this for morethan 200 fields.
Is there any framework to validate individual data types and even in exception case we need to ignore that field and continue parsing for other fields? It is ok if I don't have to use Respone POJO. Any suggetsions are welcomed.
Please suggest. Thanks in Advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
