EJBs are the foundation for the rest of this book, so we took a lot of time to explain when and when not to use them, and how to deploy them. Here are the key take-away points on EJBs.
Use EJBs when you really need them.
Know why you're using EJBs.
We use Stateless Session Beans for managing transactions and Message-Driven Beans for asynchronous processing.
EJBs require a lot of extra work, but you only have to do the setup once:
Adding a new EJB Ant build script that uses XDoclet and creates the EJB JAR file.
Referencing the EJB JAR in application.xml.
Adding the EJB JAR file to the EAR.
After the initial setup, things get better. The extra programming artifacts required by EJB 2.1 (Home and Component Interfaces and the deployment descriptors) are tedious and error-prone, but you can generate everything with XDoclet.
Under EJB 2.1, you still have to implement the callback methods by hand.
With EJB 3.0, the programming artifacts and callback methods go away. So, you're left with a business interface and a simple POJO that contains only the business methods that you care about. EJB 3.0 will streamline EJB development and deployment. We hope that a simpler EJB spec will encourage developers and architects to consider EJBs for their future needs when it makes sense to use them.
We moved our business logic from the Controller Servlet into the InventoryFacade Stateless Bean for the following reasons:
Running our code from within an EJB enables us to use Container-Managed Transactions (CMT), which greatly reduces the amount of code you have to write.
Since we may not always have a web client, we want other types of clients to use our encapsulated business logic as services. We can expose some of the InventoryFacadeBean's methods as Web Serviceswe'll show you how to do this in the Web Services chapter.
When using Hibernate 3 from within an EJB that uses CMT, remember to do the following:
Make sure that your EJB method runs within the scope of a transaction.
Get a Hibernate Session by using the Session Factory's getCurrentSession( ) method.
The Hibernate transaction API calls are no longer needed because the container manages the transactions.
Never close your Hibernate Session because doing this loses your changeslet the container do it for you.
The InventoryFacadeBean's buyCar( ) method encapsulated a Container-Managed Transaction that involved both the CAR and ACCOUNTING tables.