10 Managing data


This chapter covers

  • Examining the lifecycle and states of objects
  • Working with the EntityManager interface
  • Working with the Jakarta Persistence API
  • Working with detached state

You now understand how ORM solves the static aspects of the object/relational mismatch. With what you know so far, you can create a mapping between Java classes and an SQL schema, solving the structural mismatch problem. We remind that the paradigm mismatch covers the problems of granularity, inheritance, identity, association, and data navigation. For a deeper review, see section 1.2.

An efficient application solution requires something more: you must investigate strategies for runtime data management. These strategies are crucial to the performance and correct behavior of the applications.

In this chapter, we analyze the life cycle of entity instances—how an instance becomes persistent, and how it stops being considered persistent—and the method calls and management operations that trigger these transitions. The JPA EntityManager is the primary interface for accessing data.

Before we look at the API, let’s start with entity instances, their life cycle, and the events that trigger a change of state. Although some of the material may be formal, a solid understanding of the persistence life cycle is essential.

10.1 The persistence life cycle

10.1.1 Entity instance states

10.1.2 The persistence context

10.2 The EntityManager interface

10.2.1 The canonical unit of work

10.2.2 Making data persistent

10.2.3 Retrieving and modifying persistent data

10.2.4 Getting a reference

10.2.5 Making data transient

10.2.6 Refreshing data

10.2.7 Replicating data

10.2.8 Caching in the persistence context

10.2.9 Flushing the persistence context

10.3 Working with detached state

10.3.1 The identity of detached instances

10.3.2 Implementing equality methods

10.3.3 Detaching entity instances

10.3.4 Merging entity instances

10.4 Summary