Java Reference
In-Depth Information
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 ob-
jects 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 dis-
cuss 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
In a sense, the
EntityManager
is the bridge between the OO (object-oriented) and rela-
tional worlds, as depicted in
figure 10.1
.
When you request that a domain entity be created,
the
EntityManager
translates the entity into a new database record. When you request