Find this tutorial in:
Try the Tutorial
Stateless sessions make database queries and updates robust by setting transaction boundaries at each business method. Thisbean example annotates a single business method with a SUPPORTS transaction attribute, marking the method as a read-only transaction boundary.
A Hello, World example for EJB 3.0 is much simpler than for earlier versions of EJB. To implement the EJB you need to implement:
To configure Resin to be a server for the EJB you need to:
In this tutorial, a simple "Hello" EJB is created and deployed within Resin.
The remote interface defines the client view of the bean. It declares all the business methods. Our only business method is the hello method.
The second class for EJBs is the bean implementation class. It implements the functionality provided by the remote interface.
The @Stateless annotation marks the bean as a stateless session bean. Resin will create a stub implementing Hello and store it in JNDI at "java:comp/env/ejb/HelloBean".
The @Stateless annotation can have an optional name value which overrides the default name of "HelloBean".
The @javax.ejb.Inject annotation tells Resin to lookup the greeting from JNDI when the session bean is created. The JNDI name will be java:comp/env/greeting.
In this example, the greeting is configured with an <env-entry> in the web.xml.
The EJB 3.0 draft spec's dependency injection is somewhat inflexible since the greeting is required to be in JNDI. Resin offers a more flexible dependency injection configuration based on the configuration file. By setting the value in the configuration file, Resin's alternate dependency injection adds more flexibility and some clarity.
Managing transactions is the primary purpose of stateless session beans. Transactions are a more powerful version of a synchronized lock used to protect database integrity. @TransactionAttribute marks the transaction boundary for each business method.
The hello() business method uses SUPPORTS because it's a read-only method. It doesn't need to start a new transaction on its own, but will participate in any transaction that already exists.
The REQUIRED transaction value starts up a new transaction if none already exists. It's used when updating database values.
<ejb-server> configure the Resin EJB server. Typically it configures the EJB root using jndi-name and configures a number of EJB classes using <bean>. The <bean> entry will look at the bean's annotations to enhance the class.
The <bean> can optionally configure the bean instances with an <init> tag as described in the alternate dependency injection section.
The @EJB annotation tells Resin to lookup the session bean in JNDI with name "java:comp/env/ejb/HelloBean".
The servlet could also lookup the Hello bean with JNDI in the init() method or use an <init> configuration in the web.xml: