Search code examples
javahibernatehibernate-mapping

Why to use Hibernate Mapping Component?


I am learning hibernate an I came across Hibernate Mapping Component. Why should we use it if we can have the same pojo class for student and address?


Solution

  • You can. But that doesn't mean you want.

    Reason one: you want to model them differently

    In objects you want to model something the best possible way. That means one thing are Students and other Addresses. In a future you could have more Address per student, or none, so migration to that model will be easier if you have two differents objects.

    Think of it as high cohesion and low coupling (good design patterns). Each class has its meaning, its responsability, its limited range of action. The more isolated classes are, the more punctual changes will be. The more modular your code will be too.

    By contrast, in tables you make concessions in order to gain performance and more direct queries. That means you can denormalize your model (like joining students and addresses).

    Reason two: legacy models

    By example. If you have a legacy single table and want to use two objects, you need this mapping. Or... if your application is already made, based on two objects, but your database is reengineered and you decide one table is better.