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.

Understanding Collection Mapping of Basic Value types:

  • What we have to understand about collection mapping is, collection mapping means mapping group of values to the single field or property. But we can’t store list of values in single table column in database. We have to understand the database tables design.
  • See the below tables User and Contacts. Here Contacts table having two columns ID and CONTACT_NO and both are primary keys.
  • Here ID and CONTACT_NO are owing by User table. Contacts table not having its own identity. ID column not primary key of Contacts table, the value of ID is primary key of User table.
  • And most importantly the relationship between User and Contacts table seems One-to-Many, but it’s not true because there is no foreign key relationship between these two tables.

Java code for mapping collection of Basic Value Types :


  • Observe line numbers 27,28,29 from above code, @ElementCollection and @CollectionTable(name=“Contacts”joinColumns=@JoinColumn(name=“ID”)) explains the mapping collection of basic value types.

@ElementCollection :

  •   Defines a collection of instances of a basic type or embeddable class. Must be specified if the collection is to be mapped by means of a collection table. This annotation will be used to map collection basic value type or collection of Embeddable types.

@CollectionTable :

  • Specifies the table that is used for the mapping of collections of basic or embeddable types. Applied to the collection-valued field or property.

@JoinColumn :

  • In this Example @JoinColumn annotation used to map User entity Id  value(Primary key value) to the Contacts collection table’s ID column.
  • I will discuss more about @JoinColumn annotation in association mapping section.
To understand Hibernate Entity Types and Value Types see Entity Types vs Value Types
Download Application – (18 KB)