Uploaded on

Enterprise Java Beans 3 Basics

Enterprise Java Beans 3 Basics

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
1,830
On Slideshare
0
From Embeds
0
Number of Embeds
35

Actions

Shares
Downloads
75
Comments
0
Likes
3

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. An Overview of Enterprise Bean World
  • 2. The EJB component are server-side componentsthat encapsulate application behavior such asbusiness logic and persistence code.There are three types of EJB components: sessionbeans, message-driven beans, and entities.Session beans and message-driven beans are usedto implement business logic in an EJBapplication, while entities are used for persistence.EJB components reside inside the EJB container.Together, the components, or EJBs, and thecontainer can be viewed as a framework providingservices.
  • 3. Metadata annotations are used to preconfigurethe EJBs by specifying the type of services toadd when the container deploys the EJBs.Annotations are used to specify the type of theEJB component and to specify the services.
  • 4. In a layered architecture, components aregrouped into tiers.Each tier in the application has a well-definedpurpose.Each layer delegates the work to a layerunderneath it.EJB allows to build applications using twodifferent layered architectures: the traditionalfour-tier architecture and domain-driven design(DDD).
  • 5. The presentation layer is responsible for rendering thegraphical user interface (GUI) and handling user input.The presentation layer passes down each request forapplication functionality to the business logic layer.The business logic layer is the heart of the application andcontains workflow and processing logic.It models the distinct actions or processes the applicationperforms.The business logic layer retrieves data from and saves datainto the database by utilizing the persistence tier.The persistence layer provides a high-level object-oriented(OO) abstraction over the database layer which typicallyconsists of a relational database management system(RDBMS).
  • 6. EJB provides support for implementing the businesslogic and persistence layers.Session beans and message-driven beans (MDBs)reside in and use the services in the business logic tierwhile entities reside in and use services in thepersistence tier.The traditional architecture undermines the OO idealof modeling the business domain as objects thatencapsulate both data and behavior.It focuses on modeling business processes instead ofthe domain tending the business logic to look morelike a database-driven procedural application than anOO one.
  • 7. DDD emphasizes that domain objects shouldcontain business logic and should not just be adumb replica of database records.The domain objects are known as entities inEJB 3.The entities defined by EJB 3 Java PersistenceAPI (JPA) support OO features, such asinheritance or polymorphism.Entities are used to model domain objects,including modeling state and behavior.
  • 8. Ease of use: It doesn’t demand that tounderstand the theoretical intricacies.Integrated solution stack: It offers seamlessintegration with other J2ee technolgies and acomplete stack of server solutions, includingpersistence, messaging, lightweight scheduling,remoting, web services, dependency injection(DI), and interceptors.Open Java EE standard: EJB 3 has an open,public API specification and is developed by theJava Community Process (JCP).
  • 9. Broad vendor support: EJB is supported by alarge and diverse variety of independentorganizations.Stable, high-quality code base: a relativelystable code base that has lived through some ofthe most demanding enterprise environments.Clustering, load balancing, and failover: EJBapplication servers have a proven track recordof supporting some of the largest high-performance computing environments.
  • 10. Each bean type serves a purpose and can use aspecific subset of EJB services.The purpose of bean types is to safeguard againstoverloading them with services that cross wires.Session beans and message-driven beans (MDBs) liveand managed by the container, and are used to buildbusiness logic.Entities are used to model the persistence part of anapplication and persistence provider manages entities.A persistence provider is pluggable within thecontainer and is abstracted behind the JavaPersistence API (JPA).
  • 11. A session bean is invoked by a client to perform a specificbusiness operation.A session bean instance is available only for the duration of a“unit of work” and does not survive a server crash orshutdown.There are two types of session beans: stateful and stateless.A stateful session bean automatically saves bean state betweenclient invocations.A stateless session bean does not maintain any state andmodels the application services that can be completed in asingle client invocation.A session bean can be invoked either locally or remotely usingJava RMI.A stateless session bean can be exposed as a web service.
  • 12. MDBs process the business logic.Clients never invoke MDB methods directly.MDBs are triggered by messages sent to amessaging server, which enables sendingasynchronous messages between systemcomponents.MDBs are typically used for robust systemintegration or asynchronous processing.
  • 13. Entities are the Java objects that are persistedinto the database.Entities model lower-level application conceptsthat high-level business processes manipulate.Entities are OO representations of theapplication data stored in the database andhence survives container crashes and shutdown.JPA entities support OO capabilities, includingrelationships between entities, inheritance, andpolymorphism.
  • 14. The JPA EntityManager interface manages entities interms of actually providing persistence services.The EntityManager interface reads the ORM metadata foran entity and performs persistence operations.The EntityManager knows how to add entities to thedatabase, update stored entities, and delete and retrieveentities from the database.JPA provides the ability to handle lifecycle management,performance tuning, caching, and transactionmanagement.JPA provides a specialized SQL-like query language calledthe Java Persistence Query Language (JPQL) to search forentities saved into the database.
  • 15. The EJB container: The EJB container transparentlyprovides EJB component services such astransactions, security management, remoting, andweb services support.In EJB 3, the container provides services applicable tosession beans and MDBs only.The persistence provider: JPA provides persistenceservices such as retrieving, adding, modifying, anddeleting JPA entities when you explicitly ask for themby invoking EntityManager API methods.
  • 16. Service Applies ToIntegration Session beans and MDBsPooling Stateless session beans, MDBsThread-safety Session beans and MDBsState management Stateful session beansMessaging MDBsTransactions Session beans and MDBSecurity Session beansInterceptors Session beans and MDBsRemote access Session beansWeb services Stateless session beansPersistence EntitiesCaching and Performance Entities
  • 17. package ejb3inaction.example;public interface HelloUser {public void sayHello(String name);}package ejb3inaction.example;import javax.ejb.Stateless;@Statelesspublic class HelloUserBean implements HelloUser {public void sayHello(String name) {System.out.println("Hello " + name + " welcome to EJB3!");}}
  • 18. Simplified programming model: EJB 3 enables to developan EJB component using POJOs and POJIs that knownothing about platform services.Annotations instead of deployment descriptors: EJB 3allows us to use metadata annotations to configure acomponent instead of using XML deployment descriptorsDependency injection vs. JNDI lookup: JNDI lookups havebeen turned into simple configuration using metadata-based dependency injection (DI). E.g. @EJB annotationinjects EJB into the annotated variable.Unit-testable POJO components: EJB 3 components arePOJOs, and can be easily be executed outside thecontainer using testing frameworks such as JUnit orTestNG.
  • 19. EJB 3 manipulates metadata-based POJOs through theEntityManager interface and avoids carrying burden ofremote access.Standardized persistence: EJB 3 solidifies automatedpersistence with JPA providing robust ORMconfiguration, JPQL standardizing divergent OR querytechnologies and EntityManager API standardizingORM CRUD operations.The cleanly separated Java Persistence API: JPA acleanly separated API running outside EJB container.Better persistence-tier OO support: EJB 3 entities haverobust OO support as they are POJOs and JPA ORMmapping scheme is designed with OO, JPQL supportingOO as well.
  • 20. Annotations “attach” additional information(attributes) to a Java class, interface, method, orvariable.An annotation is a special kind of interface, it must beimported from where it is defined.EJB 3 allows to override annotations with XMLdeployment descriptors where appropriate.A deployment descriptor is simply an XML file thatcontains application configuration information.Deployment descriptor entries override configurationvalues hard-coded using annotations into EJBcomponents.
  • 21. Annotations Usage Usejavax.annotation.Resource Dependency injection of resources EJB, web,app clientjavax.ejb.EJB Dependency injection of sessionbeansEJB, web,app clientjavax.jws.WebServiceRef Dependency injection of webservicesEJB, web,app clientjavax.persistence.PersistenceContext Dependency injection ofcontainer-managed EntityManagerEJB, webjavax.persistence.PersistenceUnit Dependency injection ofEntityManagerFactoryEJB, webjavax.annotation.PostConstruct Lifecycle method EJB, webjavax.annotation.PreDestroy Lifecycle method EJB, webjavax.annotation.security.RunAs Security EJB, webjavax.annotation.security.RolesAllowed Security EJBjavax.annotation.security.PermitAll Security EJBjavax.annotation.security.DenyAll Security EJBjavax.annotation.security.DeclareRoles Security EJB, web
  • 22. Goal of dependency injection (DI) is to make componentinterdependencies as loosely coupled as possible.One component calls another component or resource onlythrough an interface.The DI is JNDI lookup model reversed.In previous JNDI lookup model, the bean explicitly retrievesthe resources and components which are hard-coded in thebean.In DI, the container reads the target bean configuration andgets the beans and resources needed by bean and injectsthem into the bean at runtime.It lets the container deal with the complexities of serviceor resource instantiation, initialization, sequencing, andsupplies the service or resource references to the clients asrequired.
  • 23. Stateless session beans are used to model actions orprocesses that can be done in one shot.@Stateless—The @Stateless annotation tells the EJBcontainer that declared Bean is a stateless session bean.The container automatically provides such services tothe bean as automatic concurrency control, threadsafety, pooling, and transaction management.@Local—The @Local annotation on the interface tellsthe container that the implementing EJB can beaccessed locally through the interface. Alternatively,when marked with @Remote annotation, remote accessthrough the @Remote annotation is provided under thehood by Java Remote Method Invocation (RMI).
  • 24. import javax.ejb.Stateless;import ejb3inaction.example.persistence.Bid;@Statelesspublic class PlaceBidBean implements PlaceBid {public PlaceBidBean() {}public Bid addBid(Bid bid) {System.out.println("Adding bid, bidder ID=" + bid.getBidderID()+ ", item ID=" + bid.getItemID() + ", bid amount="+ bid.getBidAmount() + ".");return save(bid);} ….}...import javax.ejb.Local;import ejb3inaction.example.persistence.Bid;@Localpublic interface PlaceBid { Bid addBid(Bid bid); }
  • 25. public class PlaceBidServlet extends HttpServlet {@EJBprivate PlaceBid placeBid;public void service(….) {Bid bid = new Bid();bid.setBidderID(bidderID); ……..placeBid.addBid(bid);}}When the servlet container sees the @EJB annotation as servletis first loaded, it looks up the PlaceBid EJB behind the scenesand sets the placeBid variable to the retrieved EJB reference.If necessary, the container will look up the EJB remotely overRMI by running the client in the application client container.The application client container is a mini Java EE container thatcan be run from the command line
  • 26. The @EJB annotation makes the container“instantiate” the placeBid variable with the EJB namedPlaceBid before the variable is available for use.JNDI is the container registry that holds references toall container-managed resources such as EJBs.Clients gain access to session beans like the PlaceBidEJB directly or indirectly through JNDI as follows:Object ejbHome = newInitialContext().lookup("java:comp/env/PlaceBid");PlaceBidHome placeBidHome = (PlaceBidHome)PortableRemoteObject.narrow(ejbHome, PlaceBidHome.class);PlaceBid placeBid = placeBidHome.create();
  • 27. Stateful session beans guarantee that a client canexpect to set the internal state of a bean and count onthe state being maintained between any number ofmethod calls.The container ensures that a client can reach a beandedicated to it across more than one methodinvocation.The container ensures that bean instance variablevalues are maintained for the duration of a sessionwithout your having to write any session maintenancecode.In a stateful bean, the data the user enters at each stepcan be cached into bean variables until the workflowcompletes.
  • 28. import javax.ejb.*;@Statefulpublic class PlaceOrderBean implements PlaceOrder {private Long bidderID;private List<Long> items;private ShippingInfo shippingInfo;private BillingInfo billingInfo;public PlaceOrderBean () { items = new ArrayList<Long>(); }public void setBidderID(Long bidderId) { this.bidderId = bidderId; }public void addItem(Long itemId) { items.add(itemId); }…..@Removepublic Long confirmOrder() {Order order = new Order(); order.setBidderId(bidderId);order.setItems(items); order.setShippingInfo(shippingInfo);order.setBillingInfo(billingInfo); saveOrder(order);billOrder(order); return order.getOrderId();}
  • 29. The @Remove annotation marks the end of theworkflow modeled by a stateful bean.The container is told that there is no longer a needto maintain the bean’s session with the client afterthe confirmOrder method is invoked.If the container is never told what methodinvocation marks the end of the workflow, thecontainer could wait for a long time until it couldsafely time-out the session.Since stateful beans are guaranteed to bededicated to a client for the duration of a session, alot of “orphaned” state data is consuming theprecious server resources for long periods of time.
  • 30. @Statefulpublic class PlaceOrderBean implements PlaceOrder {@Resource(name="jms/QueueConnectionFactory")private ConnectionFactory connectionFactory;@Resource(name="jms/OrderBillingQueue")private Destination billingQueue;@Removepublic Long confirmOrder() {Order order = new Order();order.setBidderId(bidderId);order.setItems(items);saveOrder(order);billOrder(order);return order.getOrderId();}
  • 31. private billOrder(Order order) {try {Connection connection = connectionFactory.createConnection();Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);MessageProducer producer =session.createProducer(billingQueue);ObjectMessage message = session.createObjectMessage();message.setObject(order);producer.send(message);producer.close();session.close();connection.close();} catch(Exception e){ e.printStackTrace(); }
  • 32. The @Resource annotation is much moregeneral purpose and can be used to injectanything that the container knows about.The name parameter values specify whatresources are bound to the EJB’s environmentnaming context.
  • 33. @MessageDriven( activationConfig = {@ActivationConfigProperty(propertyName="destinationName",propertyValue="jms/OrderBillingQueue") } )public class OrderBillingMDB implements MessageListener {public void onMessage(Message message) {try {ObjectMessage objectMessage = (ObjectMessage) message;Order order = (Order) objectMessage.getObject();try {bill(order); notifyBillingSuccess(order);order.setStatus(OrderStatus.COMPLETE);} catch (BillingException be) {notifyBillingFailure(be, order);order.setStatus(OrderStatus.BILLING_FAILED);} finally { update(order); }} catch (Exception e) { e.printStackTrace(); }}
  • 34. MDBs are not guaranteed to maintain state.The @MessageDriven annotation makes the containertransparently provide messaging and other EJBservices into a POJO.The activation configuration properties nested insidethe @MessageDriven annotation informs MDB aboutthe JMS destination to receive messages.MDBs implement the javax.jms.MessageListenerinterface which is used by container to invoke theMDB.The onMessage method defined by the interface has asingle javax.jms.Message parameter that the containeruses to pass(forward) a received message to the MDB.
  • 35. The JPA EntityManager interface defines the API for persistencewhile JPA entities specify how application data is mapped to arelational database.The @Entity annotation signifies the fact that the Class is a JPAentity.The @Table annotation tells JPA that the JPA entity is mapped tothe corresponding SQL tableThe @Column annotations indicate which Entity properties mapto which SQL table fields.The field mappings could have been placed directly ontomember variables exposed through nonprivate accessmodifiers.The @Id annotation marks the corresponding property as theprimary key for the Bid entity.The @GeneratedValue allows to automatically generate theprimary key when the entity is saved into the database.
  • 36. @Entity@Table(name="BIDS")public class Bid implements Serializable {private Long bidID;private Long itemID;@Id@GeneratedValue(strategy=GenerationType.AUTO)@Column(name="BID_ID")public Long getBidID() { return bidID; }public void setBidID(Long bidID) { this.bidID = bidID; }@Column(name="ITEM_ID")public Long getItemID() { return itemID; }public void setItemID(Long itemID) { this.itemID = itemID; }
  • 37. The JPA EntityManager performs saving of the entityinto the database by reading ORM configuration andproviding entity persistence services through an API-based interface.The manager reads the ORM mapping annotations like@Table and @Column on the entity and figures out howto save the entity into the database.The EntityManager is injected into the PlaceBid beanthrough the @PersistenceContext annotation.The unitName parameter of the @PersistenceContextannotation points to the persistence unit of application.A persistence unit is a group of entities packagedtogether in an application module.
  • 38. The save method of EntityManager presists the datainto the database issuing an SQL statement to insert arecord in DB.public class PlaceBidBean implements PlaceBid {@PersistenceContext(unitName="actionBazaar")private EntityManager entityManager;…..private Bid save(Bid bid) {entityManager.persist(bid);return bid;}}