Java Reference
In-Depth Information
involves transferring money from one account to another. Two opera-
tions are involved: withdrawing from one account and depositing to the
other account. These must both go through or both be canceled. Other-
wise, what happens if the withdrawal works but the deposit fails? The
account holder loses the money.
To prevent that from happening, the transaction begins, the withdrawal
and deposit operations are carried out, and only if all goes well is the
transaction committed to the database. If something goes wrong during
the operations, the transaction is rolled back, and the database is left
unchanged.
With JPA, you are responsible for beginning, committing, and rolling
back transactions. But hold on—Stripersist already does two out three
of those for you. Every time you call Stripersist.getEntityManager ( ), Striper-
sist begins the transaction (unless it's already active). At the very end
of each request, Stripersist automatically rolls back the transaction if
it wasn't committed. So, all you really need to do is to commit trans-
actions after modifying the database and make sure to use a Redirec-
tResolution , as we discussed Section 3.7 , The Redirect-After-Side-Effect
Pattern, on page 67 .
We're now ready to implement the save ( ) and delete ( ) methods in the
base DAO:
Download email_23/src/stripesbook/dao/impl/stripersist/BaseDaoImpl.java
@SuppressWarnings("unchecked")
public void save(T object) {
Stripersist.getEntityManager().persist(object);
}
public void delete(T object) {
Stripersist.getEntityManager().remove(object);
}
public void commit() {
Stripersist.getEntityManager().getTransaction().commit();
}
Wow, after all that theory, there's not much to the code, is there? In
both methods, Stripersist.getEntityManager ( ) implicitly begins a transac-
tion. We either save or delete the model object (which JPA calls persist ( )
and remove ( )), and the client code is responsible for committing the
transaction with a call to commit ( ) on the Dao interface. Done and done!
Our base DAO now fully implements the generic DAO interface. Before
moving on to the specific DAOs, let's add a couple of convenience meth-
ods to the base for finding objects that match a given field.
 
 
Search WWH ::




Custom Search