Below, you’ll find a few exercises to help you expand on and consolidate what you’ve learned about JPA so far.
9.1 Replace JPQL Queries with Criteria API
In our services so far, database queries have been executed with NamedQueries. To practice, create an alternative implementation of the CampaignServiceBean that uses the Criteria API instead. Proceed as follows:
- Create a copy of the class
CampaignServiceBeanand call itCriteriaCampaignServiceBean. - Designate the existing
CampaignServiceBeanas an alternative implementation that should not be used (see chapter 5 in Cloud Tutorial CDI in a Day). - Remove all invocations of
createNamedQueryin theCriteriaCampaignServiceBeanand replace them with an equivalent use of the Criteria API.
In section 7.4, we learned about the EntityListener. Use this functionality now to store the time of creation for all entities. Proceed as follows:
- Derive all entities from a new class,
DateEntity. This contains an attribute,createdAt, for saving the date of creation. - Create a corresponding
EntityListenerand use it to annotate all entities.
9.2 Validate the Minimum Donation Amount for a Campaign
In the Campaign class, we defined an attribute, donationMinimum, to store the minimum donation amount for a campaign. Currently, however, this is not checked when a donation is added.
Add this validation to the method addDonation within the class DonationServiceBean. If the validation fails, throw a RuntimeException. This will lead to the transaction being aborted, which means that no donation will be stored in the database.
9.3 Inform Organizer When Donation Targets Are Met
In the Campaign class, we defined an attribute, donationTarget to store the donation target for the campaign. At the moment, however, this is not being used.
A meaningful extension of the application would be to have it send the organizer an email as soon the current donation total reaches or exceeds the donation target for the campaign. Proceed as follows:
- Add the missing validation (for the donation target) to the
addDonationmethod in the classDonationServiceBean. As a first step, only create a log message for the donation target being reached. - Create a utility class for sending emails (see Java Mail API).
Finally, modify the method addDonation to send an email to the organizer of a campaign when the target donation is reached.
Discussion
Use the message board below to give the authors your feedback or to discuss this page’s topic with other readers (in English please!). Please don’t expect the authors to answer directly, but they might update the content of this site according to your feedback.