Say there is a LOV of departments. User will select one department, and employees connected with that department will be displayed in the table below.
Then there will be a button to create an employee. Once entering the data, the user will press Save button. Now there is a validation where the application will check that a department cannot have more than 5 employees.
I want to know how to create, and where to create such a validation rule, and how?
No. You didn't get it. The user will enter the details, and when he clicks on SAVE button, the validation should get fired to check the number of employees for that department. If the entered employee is the 6th employee for that particular department, then it should display an error message saying that there cannot be more than 5 employees.
You can create a custom method in managed bean. And on the action of the Save button, call that method and check the row count for particular department.
Also you can disable the save button from this method once the row count is reached its value.
Sorry to rain on the parade here, but I don't believe that any of these solutions will work correctly, at least not if your application has more than one user.
There is one way (short of using explicit locking, which is a bad idea for a web app) that I know of to implement such a requirement - it would involve creating a refresh-on-commit materialised view in the database and placing a check constraint on the MV. The MV would simply be something like "select department_no, count(*) num_employees from employees group by department_no" and the check constraint would ensure that num_employees must be less than or equal to 5.