Chapter 8. Components = Composition mapping

Table of Contents

Composition versus entity relations
Composed class in one table
Composition as set of many classes
Equals implementation
Composition as list of many classes
Advanced details
Composition 1:n:1
Not included mappings

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>();

Composition versus entity relations

There are two characteristics of components:

  • Dependent lifecycle
  • Shared references are not supported

If an object has a dependent lifecycle, it will be deleted when the parent object is deleted.

Some examples:

  • Shop order and order position
  • Person and address
  • Product and product details

Some examples for independent lifecycles:

  • Customer and key accounter
  • Order and article
  • Football team and player.

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.

Recommendation

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.

Keep in mind

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 .