can be set, as is done in this example. Second, the application can periodically call the
flush() method of the entity manager, which will cause all batched statements to be ex-
Table 11-2 shows the effect of the statement reuse and batching to create and write stock en-
tities into the database.
Table 11-2. Seconds required to insert data for 128 stocks via JPA
No batching, no statement pool 240 seconds
No batching, statement pool
Batching, no statement pool
Batching, statement pooling
1. JPA applications, like JDBC applications, can benefit from limiting the number of
write calls to the database (with the potential trade-off of holding transaction
2. Statement caching can be achieved either at the JPA layer or the JDBC layer.
Caching at the JDBC layer should be explored first.
3. Batching JPA updates can be done declaratively (in the persistence.xml file), or
programmatically (by calling the flush() method).
Optimizing JPA Reads
Optimizing when and how JPA reads data from the database is much more complicated than
it might seem. That's because JPA will cache data in the hope that it might be used to satisfy
a future request. That's usually a good thing for performance, but it means that the JPA-gen-
erated SQL that is used to read that data may seem, on the face of it, suboptimal. The data re-