in JPA

JPA Tutorial – @ElementCollection with basic types and embeddable

When entity has collection of basic types @ElementCollection must be used.

@ElementCollection with Basic Type

We have Pomodoro entity that has collection of tags.

Pomodoro Entity

Two tables will be created for this case PM_POMODORO  and PM_POMODORO_TAGS  tables. Here is the create SQL :

Observe the foreign key POMODORO_ID_  in PM_POMODORO_TAGS  table that is properly named as it is specified by @CollectionTable .

@JoinColumn has additional properties that you can use

  •  unique ( default is false) , defines uniquness
  • nullable (default is true), defines nullability
  • insertable and updatable, defines whether this column should be used in insert and update statements.
  • columnDefinition, defines SQL fragment that is used for generation of DDL for column. Here is one example of the value  VARCHAR(32) .

@ElementCollection with Embeddable

What if Tag is not a simple string but a Embeddable entity with two properties, name and the color? We will add TagEntity and annotate it with @Embeddable

Pomodoro entity is changed a bit

POMODORO_TAG table create SQL

@ElementCollection with java.util.Map

Element collection can be used with Map as well, for this we can use basic example of the Contact that has multiple phone numbers. For example home, work and other number.

Here we need to specify multiple annotations

  • @ElementCollection to specify fetch type
  • @Column, to specify name of the column that will hold the phone number
  • @CollectionTable, to specify the name of the table
  • @MapKeyColumn to specify the key column name( key is the phone type)

Lets check the PHONES table create SQL

Problem with upper example is that we have limited number of relationships( phone types in this case) so we should be using enumeration. Here is how to do this.

@MapKeyEnumerated annotation is used to specify how the PHONE_TYPE will be saved into the database, as

  • ordinal (0, 1, 2)
  • name (HOME,WORK,OTHER)

Write a Comment