Java Reference
In-Depth Information
As mentioned earlier, all persistence operations that require database updates must be in-
voked within the scope of a transaction. If an enclosing transaction isn't present when the
persist
method is invoked, a
TransactionRequiredException
is thrown for a
transaction-scoped entity manager. The same is true for the
EntityManager'
s
flush
,
merge
,
refresh
, and
remove
methods.
10.2.2. Retrieving entities by key
JPA supports several ways to retrieve entity instances from the database. By far the simplest
to retrieve the
Seller
instance corresponding to the
Item
to add:
Seller seller = entityManager.find(Seller.class, sellerId);
In this line of code, the first parameter of the
find
method specifies the Java type of the
entity to be retrieved. The second parameter specifies the identity value for the entity in-
stance to retrieve. Recall from
chapter 9
that an entity identity can either be a simple Java
type identified by the
@Id
annotation or a composite primary key class specified through
method is passed a simple
java.lang.Long
value matching the
Seller
entity's
@Id
annotated identity,
sellerId
.
composite primary keys. To see how this code might look, assume for the sake of illus-
tration that the identity of the
Seller
entity consists of the seller's first and last names
instead of a simple numeric identifier. This identity is encapsulated in a composite primary
key class annotated with the
@IdClass
annotation. The following listing shows how this
identity class can be populated and passed to the
find
method.
Listing 10.4. Find by primary key using composite keys
SellerPK sellerKey = new SellerPK();
sellerKey.setFirstName(firstName);
sellerKey.setLastName(lastName);
Seller seller = entityManager.find(Seller.class, sellerKey);