Example
The following shows a basic example of what an EJB looks like in code:
@Stateless public class CustomerService { @PersistenceContext private EntityManager entityManager; public void addCustomer(Customer customer) { entityManager.persist(customer); } }The above defines a service class for persisting a Customer object (via O/R mapping). The EJB takes care of managing the persistence context and the addCustomer method is transactional and thread-safe by default. As demonstrated, the EJB focuses only on business logic and persistence and knows nothing about any particular presentation.
Such an EJB can be used by a class in e.g. the web layer as follows:
@Named @RequestScoped public class CustomerBacking { @EJB private CustomerService customerService; public String addCustomer { customerService.addCustomer(customer); context.addMessage(...); // abbreviated for brevity return "customer_overview"; } }The above defines a JavaServer Faces (JSF) backing bean in which the EJB is injected by means of the @EJB annotation. Its addCustomer method is typically bound to some UI component, like a button. Contrary to the EJB, the backing bean does not contain any business logic or persistence code, but delegates such concerns to the EJB. The backing bean does know about a particular presentation, of which the EJB had no knowledge.
Read more about this topic: Enterprise JavaBeans
Famous quotes containing the word example:
“Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.”
—Marcel Proust (18711922)