'Validation size of set in @ManyToMany relation

that I have students and courses. There is relation @ManyToMany between them. But student can only enroll at 5 courses and course can have only 50 students. Any ideas how to do validation here? I can't check it in service class, I need to do validation. I am using Set in relationship.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source