5 Mapping persistent classes


This chapter covers

  • Understanding entities and value type concepts
  • Mapping entity classes with identity
  • Controlling entity-level mapping options

This chapter presents some fundamental mapping options and explains how to map entity classes to SQL tables. This is essential knowledge to start with the structure of the classes in the application, no matter if you work with Hibernate, with Spring Data JPA, or some other persistence framework implementing the JPA specification. We demonstrate and analyze how you can handle database identity and primary keys and how you can use various other metadata settings to customize how Hibernate and Spring Data JPA using Hibernate as a persistence provider load and store instances of your domain model classes. Hibernate is a JPA implementation, while Spring Data JPA, as data access abstraction, comes on top of a JPA provider (Hibernate, for example) and will significantly reduce the boilerplate code to interact with the database. That is why, once the mapping of persistent classes is made, it may be used both from Hibernate and from Spring Data JPA. Our demonstrations emphasize these things.

All mapping examples use JPA annotations. First, though, we define the essential distinction between entities and value types and explain how you should approach the object/relational mapping of your domain model.

5.1 Understanding entities and value types

5.1.1 Fine-grained domain models

5.1.2 Defining application concepts

5.1.3 Distinguishing entities and value types

5.2 Mapping entities with identity

5.2.1 Understanding Java identity and equality

5.2.2 A first entity class and mapping

5.2.3 Selecting a primary key

5.2.4 Configuring key generators

5.2.5 dentifier generator strategies

5.3 Entity-mapping options

5.3.1 Controlling names

5.3.2 Dynamic SQL generation

5.3.3 Making an entity immutable

5.3.4 Mapping an entity to a subselect

5.4 Summary