Maven dependencies used all over JPA tutorials same. Please follow "Setting up Project" section to understand about project configuration.
persistence.xml and other code files reused from How to Persist an Entity in data base using JPA?
Each Sample application from download includes SQL file also.

Let’s understand what is composition in java :

  • Let’s assume there are two java classes called College and User. Each class having common fields street, city, state, area code.
  • To increase reusability we can extract those common fields and create a new class with those fields, called ContactAddress java class.
  • Now include ContactAddress as instance variable in College and User classes.
  • Exactly we call the relationship between College and ContactAddress OR User and ContactAfddress is called Composition.
  • Composition is HAS-A relation between two java objects. Below image illustrates composition in Java.

Now let’s understand Composite mapping in Hibernate :

  • Now let’s understand Database design. See below tables, User and College having common columns names.
  • But in java we can follow above design explained in composition.
  • What we have to understand is, ContactAddress not owning identifier (Primary Key). Here ContactAddress is composite Value Type.
  • College and User have their own identifier, they are Entity types. ContactAddress belongs to either College object or User object for each mapping.
  • In JPA terms ContactAddress is embeddable and embedded in  User and College objects.
To understand Hibernate Entity Types and Value Types see Entity Types vs Value Types

Quick Look On JPA Annotations to understand Mapping :

@Embeddable :

  • Defines a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the entity. It don’t have own identifier. In this tutorial ContactAddress is Embeddable.

@Embedded :

  • Specifies a persistent field or property of an entity whose value is an instance of an embeddable class. The embeddable class must be annotated as Embeddable. In this example ContactAddress is embedded in College and User Objects.

@AttributesOvveride :

  • Used to override the mapping of a Basic (whether explicit or default) property or field or Id property or field.

  • In Database tables observe the column names. User table having STREET_ADDRESS column and College table having STREET column. These two columns should map with same ContactAddress field streetAddress. @AttributeOverride gives solution for this.
  • To override multiple column names for the same field use @AtributeOverrides annotation.

Java code for Composite mapping :


Download Application – (18 KB)
Download Application – (13 KB)