Can hibernate validator be used to validate a field depending on a field value from another class - validation

I have a scenario where I need to validate some fields of a class depending on the value of a field from another class.
For ex: Street, City, Postal Code of Address class should not be null if the Employee has registered for a Group Retirement Plan.
Can this scenario be handled using Custom Validator of Hibernate Validator? Is this a good candidate for Hibernate Validator ? If so, could anyone provide me with some examples.
I have already gone through cross field validation examples like:
Cross field validation with Hibernate Validator (JSR 303)
If I have a boolean indicator to indicate whether a user is registered for group retirement plan in Address domain class, I know I can come up with Custom Validator to verify the fields. But, I want to avoid adding indicator to Address class. As well, Address is not a field in Employee class to do nested validation.
The Frameworks I am using are Spring MVC and Mybatis for Data access. The validation is happening at Spring Rest API call with #Valid annotation.

I guess a custom class level constraint might work, but it depends on your actual domain classes. It is currently not clear how for example Employee, Group Retirement Plan and these other entities are connected.
Whether Hibernate Validator is a good fit is whether you have other validations as well or which other frameworks are involved. For example, if you want validation to take place at JPA live cycle events, then Bean Validation is a good fit, since it integrates per specification with JPA. If you really only have this one validation, writing some custom code might be all you need.

Related

Save multiple row data and some other data into two tables simultaneously in spring hibernate

I want to save data of a form into two tables simultaneously. The form contains multiple identical rows with some fields like
item, unit, unit_price, total.
1.) In the table1 I would like to save some data like id(auto generated, primary key), date, creator.
2.) In table2 I would like to save the id(auto generated, primary key), fid(id of the table1, foreign key), item, unit, unit price, total. Remember, in table2 multiple rows will be save from the form data.
I can't figure it out. Please help me with a valid step by step example, and please don't use static or pre-defined data, take the data from form only.
Is your form an HTML form on a web page, and are you writing a Spring MVC application? Have you setup Spring Security, or some other authentication mechanism such that you know who the user is? If so, here is one approach:
Define a plain old Java object (POJO) with fields id, unit, unit-price, total, creator, currentDate; perhaps you would name it Item.
Define another plain old Java object perhaps named "ItemHistory", with its own ID and a reference to an Item.
In the first POJO ("Item") include a reference to a list of ItemHistorys.
Annotate both classes with Hibernate/JPA annotations, such that the Item has a OneToMany relationship to ItemHistory.
Define a Spring MVC controller with a method annotated as a POST method, with an Item as one parameter, and an Authentication as another parameter (supposing you have configured Spring Security, the Authentication will automatically be populated with the identity of the currently-logged-in user. In this method, set the currentDate and author of the Item to the current date and the principal from the Authentication parameter. If it is a new Item (no id yet), add the first ItemHistory as a copy of the Item itself. If it is an existing item, add another ItemHistory if needed.
Define a Spring bean, perhaps named ItemService, with a method annotated as transactional, that takes an Item and saves it. Call this bean from the REST controller. Such a Spring bean is known as a DAO (data access object).
There are other strategies, but if you already have Spring MVC, Spring Security, and Hibernate/JPA configured to your needs, this one is pretty straight-forward.

Validation in Domain Model of Domain Service?

I'm reading the book "Architecting Applications for the Enterpise (Dino Esposito)". It raised a question about validation.
The Domain Model can have a property CanBeSaved which calls the Validate() method of the Domain Model. All good, except for complex situations.
For example a Customer model which needs a unique customer code (ex. 000542). You can only check this with database access. Isn't it better to put the Validation always in a Domain Service. So you have only one way of checking if an aggregate is in a valid state? If you use both, a developer can 'forget' to use the domain service validation for the Customer.
I find it better to have always valid entities rather than rely on an external validation object.
That being said, unique checks are a bit of an exception since it is often not something that the aggregate itself can determine on its own, you have to look into all existing aggregates to see if the value is not already taken. What I do is check for availability of the value before creating the entity, and also put a constraint in the database which will verify uniqueness at persistence time. You could also try to find a domain concept that encompasses all your entities and make it an aggregate that has a list of all codes and enforces the uniqueness invariant.

is this a good idea to implement validation in entity framework POCO entities in dabtase first?

It`s seems that the best place to implement validation is as close as possible to the database, so when I use entity framework the nearest objects are the entities, in my case the POCO entities.
The reason for that is that if I want to reuse this POCO entities, the validation is implemented in the POCO objects and then there are less posibilities to insert worng data in the database.
this also avoid that someone try to insert incorrect data in the databse creating another application, or because he does not implement the validation. So it is more secure.
One way to do that is using partial classes that extends the POCO entities and that implements the IValidatableObject interface and return a list of validationresult.
But other way is the following. I have a common assembly that has the following:
One interface that declare the methods that need to implement the repositories.
The POCO entities that will be used by the repositories.
One class with utilities, such as copy entities and methods to validate the data of the entities.
Then I can create many repositories that use different versions of EF or another technology and all of them use the common assembly. This repositories implements the validation using the methods in the common library.
In this case I implement the validation only once. The only problem is that the repositories need to call the methods to validate the data.
But there are advantages in this way, from my point of view. For example, I can validate the data of the entities depending on the type of the operation. For example, if I am adding a new record and the primary key as an autonumeric, if the ID is not 0, then I can throw an exception, or if I try to delete a register when the ID is 0, then I don't need to send the command to the database.
So this second solution solves the problem to implement the validation as close as possible to the database, bacause is used in the repository, that is the element that access to the database, but has the problem that if some developer creates a new repository and not use the validation methods, I can have incorrect data in the database.
So my question is if the best option is to use validation with partial classes or to use a common library and the validation is implemented in the repositories, that is really what the users will use.
Thanks.
OK - phew, big question. My opinion is that the APPLICATION DOMAIN of the application is the boss of everything. The database is just an add-on service. So, the application domain should ultimately validate ALL objects that are being SENT somewhere. No need to validate object coming out of the DB because they were validated going in.
As an example, what if you were creating some object that needed to be sent off to a web service and it needed validation. Lets say it was never going near the database or the repositories. Once the DOMAIN business objects have been validated, they can then be sent for persistence or anywhere else.
Another thing to consider is what you mean by validation. Does it mean the datatypes are correct? Does it mean the business object is valid? Does it mean the business object is valid in the given context? It could mean all or only some of these things.
As an example, what if your system allows users to partially update records (common with very long input forms). The business object may only become valid when ALL the required data is captured, but the database allows persistence of "partial" data. In other words, you can save the business object to the database although it is not valid for further processing yet. etc etc....

ASP.NET MVC 3 Pattern for dynamic validation attributes including client side

My validation requirements for a the fields in a form are contained in an external table so that they can be updated without altering and rebuilding the code.
I have approximatley 100 fields with a mixture of validation requirements - range, required, regular expression and dependency on other fields. One example is date range validation. A date of birth field requires a date range which is between -10 years and -50 years of the current date.
I have read around the subject but have not identified a pattern for the complete solution.
I am using Visual Studio 2010 with MVC 3 and Entity Framework.
Any help with this would be gratefully received. Thanks in advance.
In a simple level I think you can still use the built-in Data-Annotations validation attributes to does the validation and for that you should map the validation rules stored in the table to the attributes.
I think all you have to do is create a custom model validation provider by inheriting the class ModelValidatorProvider. This class contains a single method called GetValidators that returns the collection validators for that model.
You have to implement the GetValidators method and in there you have to make a database call to get the validation rules for the model from the database (or from cache?) and convert them into ModelValidators. You could still use the built-in DataAnnotationsModelValidator to do the validations.
I would suggest you to look into the source code of DataAnnotationsModelValidatorProvider that will give you all the information. In that class what they are doing is basically iterating all the validation attributes applied to the model properties and converting them into ModelValidators through adapters and factories. In your case instead of attributes they are stored as records in tables and I don't think much work will be there.

How to get model data annotations to implement application validation without implementing at DB level as well using EF?

I like the idea of using the data annotations to specify validation of fields within the Model. However in EF I notice that it wants to implement this at DB level ie [Required] becomes a "not null" field. Is it possible to just have the application apply this validation without changing the database?
Thanks,
Ed
What you can do is to use a separate view model for the views and separate entity classes for the database. And you can map those objects using a library like auto mapper.

Resources