8 Mapping collections and entity associations


This chapter covers

  • Mapping persistent collections
  • Examining collections of basic and embeddable type
  • Investigating simple many-to-one and one-to-many entity associations

The first thing many developers try to do when they begin using Hibernate or Spring Data JPA is to map a parent/children relationship. This is usually the first time they encounter collections. It’s also the first time they have to think about the differences between entities and value types or get lost in the complexity of ORM.

Managing the associations between classes and the relationships between tables is at the heart of ORM. Most of the difficult problems involved in implementing an ORM solution relate to collections and entity association management. We start this chapter with basic collection-mapping concepts and simple examples. After that, you’ll be prepared for the first collection in an entity association—although we’ll come back to more complicated entity association mappings in the next chapter. To get the full picture, we recommend you read both this chapter and the next.

8.1 Sets, bags, lists, and maps of value types

8.1.1 The database schema

8.1.2 Creating and mapping a collection property

8.1.3 Selecting a collection interface

8.1.4 Mapping a set

8.1.5 Mapping an identifier bag

8.1.6 Mapping a list

8.1.7 Mapping a map

8.1.8 Sorted and ordered collections

8.2 Collections of components

8.2.1 Equality of component instances

8.2.2 Set of components

8.2.3 Bag of components

8.2.4 Map of component values

8.2.5 Components as map keys

8.2.6 Collection in an embeddable component

8.3 Mapping entity associations

8.3.1 The simplest possible association

8.3.2 Making it bidirectional

8.3.3 Cascading state