Reputation: 246
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?
Upvotes: 3
Views: 3393
Reputation: 11
One more point is that Address (which is treated as component here) cannot have its own primary key, it uses the primary key of the enclosing Student entity.
Upvotes: 1
Reputation: 13841
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.
Upvotes: 3