I am using MyBatis
it for all actions that involve interaction with the database. I'm also working with Angularjs for the frontend , so client-side validations are done with angular-validation-ghiscoding
and with native html5 validations. I would like to validate the data in the bankend as well , but without using annotations.
Here is an example of the code:
@RequestMapping(value = SecureApiResources.URI_UPDATE_ACCOUNT, method = RequestMethod.POST, produces = "application/json")
public @ResponseBody Account updateAccount(
@RequestBody final AccountRequestUpdate accountRequest) { // Object to be validated (accountRequest)
Account account = accountMapper.getAccountOfMerchant(authContextHolder.getMerchantId(), authContextHolder.getDefaultAccountId());
if (account == null) {
HttpErrors httpErrors = new HttpErrors(
SecureApiResources.ERROR_ACCOUNTS_NOT_FOUND);
throw new EntityNotFoundException(httpErrors);
}
int resultUpdate;
try {
// In this point I should validate the accountRequest object
account.setAccountName(accountRequest.getAccountName());
account.setCommercialName(accountRequest.getCommerciaName());
account.setCountry(accountRequest.getCountry());
account.setCity(accountRequest.getCity());
resultUpdate = accountMapper.updateMerchant(account);
if (resultUpdate == 0) {
HttpErrors httpErrors = new HttpErrors(
SecureApiResources.ERROR_ACCOUNTS_NOT_FOUND);
throw new EntityNotFoundException(httpErrors);
}
} catch (Exception e) {
HttpErrors httpErrors = new HttpErrors(
SecureApiResources.ERROR_SQL_NOT_EXECUTE);
throw new EntityNotFoundException(httpErrors);
}
return account;
}
In the same class I have a method to create an account and receive another model object ( AccountRequestCreate accountRequest
).
What can be the best option to implement without using xml or annotations?
If you don't want to use XML or annotations you have 2 options:
Prop class:
When I use this technique, I create a custom exception at the same time to handle all possible errors and return the localized message in case of internationalized applications:
The exception has to be something like this:
And to use it:
Validating setters:
Although I recommend this option less, you can take advantage of the assignments to the attributes of
Account
to validate the data that comes from the front is correct by creatingsetters
that they returnboolean
or throw exceptions:NOTE: This case only works if you don't
AccountRequestUpdate
directly persist but instead use the data to create other objects.Validating:
Throwing exception:
A good idea is to use the Spring Validator interface, annotate it as a Component (spring bean) so you can inject it and use it when you need it, on the one hand it is clean and on the other hand it is in accordance with the Spring Framework libraries.
An example implementation is as follows:
You can find more information in the following links: