Search code examples
javahibernate-validator

How to escape validation of a parent class field in child class in hibernate validator


Suppose I have one parent class:

Class Employee {

@NotNull
private String empName;

//setter and getter

}

and a child class that extends the parent:

Class ContractEmployee extends Employee  {

}

My requirement is that if I pass Employee object to hibernate validator then Not null validation should happen on empName field which is happening if I do so. But, if I pass ContractEmployee object to hibernate validator then Not null validation should not happen. How can I escape/bypass this not null validation for ContractEmployee.


Solution

  • I recommend against such a design as it violates the Liskov substituation principle. A client of the Employee contract relies on the fact that empName is not null. This invariant should not be violated by sub-types of Employee.