Chapter 10. Managing entities

 

This chapter covers

  • EntityManager
  • Entity lifecycle
  • Persisting and retrieving entities
  • Entity scopes

Chapter 9 introduced the basics of JPA entities. You saw how to implement the domain objects with JPA, define relationships between objects, and handle inheritance. In this chapter we’re going to delve into EntityManager and show how to manage entities. We’ll discuss what an EntityManager is and how to inject them into your EJB classes. You’ll learn about the lifecycle of entities and how to use EntityManager to persist, find, merge, and remove entities—the EntityManager equivalent of the basic database CRUD (create, read, update, delete) operations. You’ll also learn about the different scopes entities go through during their lifecycle.

Let’s start this chapter by examining EntityManager. EntityManager is at the heart of JPA, and practically every operation you’ll perform will depend on having an instance of EntityManager.

10.1. Introducing EntityManager

The EntityManager API is probably the most important and interesting part of the Java Persistence API. It manages the lifecycle of entities. In this section you’ll learn about the EntityManager interface and its methods. We’ll explore the entity lifecycle, and you’ll also learn about persistence contexts and their types.

10.1.1. EntityManager interface

10.2. Persistence operations

10.3. Entity queries

10.4. Summary