Table of Contents
Components can be used to implement the object-oriented concept of composition.
This kind of relation can of course also be designed using a relation to an entity. So the question is, how to choose between entity relations versus and composition?
Let’s have a look at a first example and then we will work out the criteria to choose the correct approach.
A person has an address component.
Person class.
import javax.persistence.Entity; @Entity public class Person{ private Address address;
Address class.
import javax.persistence.Embeddable; @Embeddable public class Address { private String street;
Collections of components are supported as well. A person might have a collection of former addresses.
Person class.
import javax.persistence.Entity; @Entity public class Person{ private Address address; @ElementCollection @CollectionTable(name = "person_former_addresses", joinColumns = @JoinColumn(name = "person_fk")) private Set<Address> formerAddresses = new HashSet<Address>();
There are two characteristics of components:
If an object has a dependent lifecycle, it will be deleted when the parent object is deleted.
Some examples:
Some examples for independent lifecycles:
The last case could be discussed. If the team needs to be shut down, do you really want to keep the player in the league?
A shared reference is a case of two entities having a relation to the same entity instance. For example two shop products might have a reference to the same shop category.
If a class does not need to support shared references and has a dependent lifecycle, you should map it as component, as you get the saving, updating and deleting for free.
You can always live and develop without using components. It is a just cleaner mapping.
Finally, using Cascade.ALL and orphan removal you can achieve component like behaviour with entities.
The Hibernate Reference uses the term entity relation but I believe that the term entity agregation is more precise. When speaking about composition the Hibernate Reference uses component collections. Alternatively you may speak about composition .