Java Reference
In-Depth Information
class="fancyfoods.persistence.InventoryImpl">
<tx:transaction
method="*"
value="Required" />
<jpa:context
property="entityManager"
unitname="fancyfoods" />
All method calls should
have transactions.
B
Inject persistence
context.
C
</bean>
<service
ref="inventory"
interface="fancyfoods.food.Inventory" />
Expose as
InventoryService.
</blueprint>
This creates an instance of
InventoryImpl
, performs some magic with transactions
B
, and injects the
InventoryImpl
with a
JPA
EntityManager
C
. For application-
managed persistence, an
EntityManagerFactory
could be injected instead with the
following line:
<jpa:unit property="entityManagerFactory" unitname="fancyfoods" />
PROGRAMMING WITH JPA
The
InventoryImpl
class is where you get to see the
JPA
programming model in
action. The reference to the
EntityManager
is injected, and so the
InventoryImpl
never needs to worry about creating it, closing it, or checking that it's associated with
the right persistence context:
public class InventoryImpl implements Inventory {
private EntityManager em;
public void setEntityManager(EntityManager em) {
this.em = em;
}
Writing and retrieving data
Food can be retrieved from the database and persisted to the database easily using the
JPA
API
:
@Override
public FoodImpl getFood(String name) {
return em.find(FoodImpl.class, name);
}
@Override
public void createFood(String name, double price, int quantity) {
FoodImpl food = new FoodImpl(name, price, quantity);
em.persist(food);
}
The
find()
method retrieves a persisted
FoodImpl
by its primary key, and the
persist
method writes a new or modified
FoodImpl
to the database.









