Ejb 3.0 in Simple Steps PDF

You might also like

You are on page 1of 221
ae * Anall-inclusive book to * Quick and Easy learning in teach you everything about Simple Steps Clelniceame iss ee » Easy, Effective, and worldwide for learning Reliable EIB 3. EJB 3.0 “SIMPLE —— h — eet ight. Be.portal?_nfpb=truek_pageLabel=ApoDeploymentsControPage Piha Welcome, weblogic = x ee eee 3 base_domain Dhges exist. Click the Prati bution to allow . Withe domain. Summary of Deployments Contra! Monitoring ‘This page displays a list of Java EE applications and stz ] oman. Installed applications and madules can be stax first selecting the application name and using the cont To install a new application or moduke for deployment | domain ‘(©Copyright by Dreamtech Press, 19-A, Ansari Road, Daryaganj, New Delhi-1 10002 ‘This book may not be duplicated in any way without the express written consent of the publisher, except in the form of brief excerpts or quotations for the purposes of review. The information contained herein is for the personal use of the reader and may not be incorporated in any commercial programs, ather books, databases, of any kind of software without written consent of the publisher. Making copies of this book or any portion for any ‘purpose other than your own is a violation of copyright laws. Limits of Liability/diselaimer of Warranty: The author and publisher have used their best efforts in preparing this book. The author make no representation or warranties with respect to the accuracy or completeness of the contents of this book, and specifically disclaim any implicd warranties of merchantability or fitness of any particular purpose, There are no warranties which extend beyond the descriptions contained in this paragraph, No warranty may be created or extended by sales representatives or written sales materials, The accuracy and completeness of the information provided herein and the opinions stated herein are not guaranteed or warranted to produce any particulars results, and the advice and strategies contained herein may not be suitable for every individual. Neither Dreamtech Press nor author shall be liable for any loss of profit or any other commercial damages, including bat not limited to special, incidental, consequential, or other damages. ‘Trademarks: All brand names end product names used in this book are trademazks, registered trademarks, or trade names of their respective holders, Dreamtech Press is not associated with any product or vendor mentioned in this book. ISBN: 10 —81-7722-782-3 13 — 978-81-7722-782-6 Edition: 2008 Printed at ; PrintMan (India), Delhi - 110 092 CONTENTS Chapter 1 What is Java EE 5... Java EE 5 Components. Java EE Clients.. Java EE 5 Containers. Introduction to EIB Need of EJB. Types of Enterprise Beans. SESSION BS nnennentnnnntnentnnnenssniittnnnnnnnen Entity Bean: ‘Message-Driven Bean UB 2D sa sssssnissssssnssnssssssssenssnsissssnnnsnnssnsssnnsnsssssssnssnssssssssnsnsssssnssessnsssesansnssssscsnnn lt Need of E1B3.0.. New Features of EJB 3 Annotations. Callback Methods. Dependency Injection POIO Model a... sMLsALLSLALAALLLALLABb Elimination of Hame Interface and Hame Objects. Elimination of Component Interface. interceptors Java Persistence API Summary Sa fo Tay fw de joo bow (eyelet ey mPa Life cycle of a Stateless Session Beat eran . sss susan Hements of Stateless Session Bean Developing a Stateless Session Bean Deployment .. - ses : ~ Stateful Sessi0N BROAN scenes encase nine S Life Cycle of stateful Session Bean Developing a Stateful Session Bean.. Choosing Between Stateless or Stateful Session Bean Summary EJB 3.0 in Simple Steps Messaging Concept. IMS 0.2. Why to use MDB?..... = oe oe - = Life cycle of Message Driven Beat Writing an MDB. Sample Application Deploying the EB .. Running the Application Summary ss ot tede Weis sca ane : EL) (ntreduction Transaction-Where they are found. AIM Online Book Store Medical Syste... - sane Why do we Need Transactions?... Transaction Properties Atomicity Consistency (colation Durability. Chained Transactions BS Saga Transactions Transaction Support in EJB 3.0. Java Transaction API UTA) Container-Managed Transactions. Bean-Managed Transactions . . sos Summary... ” a CCG Ccucn her utc act eee cya Untroduiction Object-Relational Mapping (ORM!) Introduction to Entity, Contents *“SIMP._.. STE Specifying the @ENTITY.. 106 ifying the @Table.. 106 Specifying the @Tabl ifying the olumns. 1 fying the @Coh 07 Specifying @Enumerated. 108 Specifying the @Lob 108, Specifying the @Tempara Entity and Session beans When To Use Entity Bean Entily class ... Entity manager API Life Cycle of Entity Entity Listeners and callbacks. Entity Listeners . Callback: Packaging a persistence UMIR 1s: sosnesees W4 ame. transaction-type... . eos PrOVIGOr suteeeetssteetsteiciansiaieaeiiiiiaeiuiianeceiaineassns 11S ta-data-saurce, non jta-data-soures Mapping. file. eo-cvonenenoenen Obtaining an Entity Manager... Session Bean using the Container Injection. Obtaining EntityManager using EntityManagerFactory Obtaining EntityManager by looking up using JNO! Creating a Sample Application .. Compiling the Java classes. Deploying the Sample Application.. Executing the Sample Application .. Summary Introduction to JPQL .. JPQL statements. . The SELECT statement 143 The UPDATE staternet Lid The DELETE statement. 144 PQL Functions... String Functions... Arithmetic function: ‘Temporal functions... SELECT clause. Er Chae sates aniessetntntannnnnininnnninnininininsnnniniisnsnssninensssssssissssssssinsienl AB WHERE clause. 149 £8 3.0 in Simple Steps viii Path expressions Using the BETWEEN operator .. Using the IN operatar.. Using the LIKE operato Using the EMPTY comparison expression JPQL collection member expression. JPQL EXISTS expressions JOIN: Inner Join . Left Outer Join. Fetch join. Query API... Defining Dynamic queries .. ‘Defining Named queries Executing Queries.. Creating a Query instanc instances.. Creating dynamic query instances... Query interface .. Parameter setting in que! Retrieving a single enti Retrieving a Collection of entitic Paginating a result list ...... Controlling the flush mode. Specifying Query hints... Summary O0-10- O00 aa ssessasseenssanenasseansssnsnsassnenaneniinnensininarseisseisininnseinicicinseenl AT One-to-Many Many-to-One.. Many-to-Many Mapping Collectian-Based Relationships. Entity Inheritanc Single table per class hierarchy Separate table per subclass... Single table per concrete entity class. Summary Contents Gna Me eR iicmeccagiaed 4 ri) £8 3.0 Timer Service... «202 ... 203 Different Types of Timers. ‘Creating Timer Objects Cancellation Expiration. Strengths and Limitations af £|8 Timer Services... Creating a Sample Application using Timer Service Deploying the E)B.. Running the Appl Summary Chapter 9 # Interceptors What are Interceptors? Interceptor Lifecycle. Specifying Interceptor: Interceptor class... Applying Interceptors through XML. Disabling Interceptors... Using Annotations. sereeeeee Programming by using the Business Methods. Programming by using the Life Cycle Call Back Methods. Specifying Default Interceptor Methods... Life cycle Call Back Methods in an Interceptor Class @Pre{estroy. @PostConstruct. © PostActivate Life Cycle Callback Interceptor Methods in a MDB.. Life Cycle Callback Interceptor Methods in a Session Bean Exception Handling. Aborting a methed invacation.. Catch and throw exceptions Summary . EJB 3.0 jot Sirmple Steps 1} Re iey Com) lotroduction Security Violations .... EIB Security. Transport Security with SSL Role-Based Security. 7 Declarative Securi ekeREEESEEERBEE Urheberrechtlich geschitztes Bild Urheberrechtlich geschitztes Material EJB 3.0 in s the small scale enterprises started growing into large scale enterprises, the distributed applications emerges. The distributed applications are the set of programs run on more than one computer and communicate through a network. Today the developing enterprise level applications which needs to be scalable, transactionaly secure, distributed. Enterprise JavaBeans (E]Bs) are basically server-side components which creating such applications. EJBs work as the Business Layer components. There are some component frameworks like EIB such as Common Object Request Broker Architecture DCOM and ActiveX/COM, We are discussing EJB component framework in this Enterprise Java Bean is just a part of Java EE specification. Hence, before introducing you EJB, let us introduce you with Java EE 5 specification for its various supported components different types of containers servicing these components. What is Java EE 5 The Java Platform, Enterprise Edition 5.0 Java EE 5) is a specificatian given by specifies standards and rules which should be followed when developing Java level applications. The main objective of Java EE is to provide an environment to tier, platform independent, secure, portable and standard enterprise applications. Java of the three different Java platforms. The three different Java platforms are: Q Java Platform, Micro Edition (Java ME): A development platfarm for the used in Java enabled devices. Q Java Platform, Standard Edition Java SE): A development platform with core lasses and interfaces which can be used by standard core applications, Java ME and applications. Q Java Platform, Enterprise Edition (Java EE): A development platform for Java enterprise level applications. This provides different technologies for the components to be designed for a large scale application for an enterprise. The Java EE specification describes standards which are independent of any platform and supports cross platform develapment and deployment, The Java EE provides a framework for building and deploying various server components. Java EE specification different technologies which are based on the technologies supported by Java SE. Java EE 5 Components Generally, an enterprise application, which has been developed using server-side designed using Java EE environment, is a multi-tiered applications. The whole divided into different segments running on different locations like client machine, enables application server, and database server. You can see Fig.£JB-1.1 to find how a application is distributed and running on different locations. Chapter 1: Introducing EJB Web Tier J2EE SERVER MACHINE Business Tier Fig EfB-1.1 A Java EE 5 application consists of the different components like Servlet, JSP, and EJBs. The different classes and interfaces have been provided under Java FE specification to create different Java EE components, Let us explain a Java EE application shown in Fig.£JB-1.1 for what is being displayed here. Q Dynamic HTML Pages: The dynamic HTML pages are the client-tier components as they are not executed on server-side. QO Servlet and Java Server Pages (JSP): These are the web-ticr components that run on the server. The Java EE 5 web tier components are Servlet, JSP pages and pages created using Java Server Faces technology. The Servlet is a Java programming class which dynamically process requests and generate responses. The Java Server Pages are the text documents, which execute as Servlet and provide a natural approach for creating dynamic content, The Java Sever Faces technology builds on Servlet and JSP technology and provides the user interface component framework for the Web applications. Q Enterprise Java Beans: These are the business components that run on the server. The needs of a particular business domain like banking, retail or finance is resolved by the business code which is also known as business logic. The business logic is handled by the Enterprise beans running in the business tier. The Enterprise bean receives the data from the client programs, then processes it and finally sends it to the enterprise information system (EIS) for storage. Moreover, the Enterprise bean also retrieves the data from storage, processes it and then sends it back to the client program. OQ Database: It stores the data about particular Web application, enterprise or company in an organized manner so that various operations like accessing data, updating data and deleting can be easily performed. The Java EE 5 Components are written in Java programming language and are compiled in the same way as any program in the Java language. The basic difference between the Java EE 5 components and standard Java classes is that the Java EE 5 components are assembled to form a Java EE 5 application with its related classes and files and these communicate with other Java EE 5 components, The Java EE 5 components are verified to be well formed and in compliance with the Java EE 5 specification and are deployed where they are run and managed by the server. EJB 3.0in Simple Steps Java EE Clients The Java EE 5 client can be of two types - the application client or the web client. An application client is a Graphical User Interface (GUI) and runs on the client machine. The application clients can directly access the Enterprise beans running in the business tier and can also open HTTP connection to create a Communication with the Servlet or the [SP page running on the web-tier as shown in Fig.EJB-1.1 The Web client can be the dynamic web pages containing markup languages like HTML, XML etc, or the web browser rendering the pages received from the server. Sometimes, the web client is also known as thin client. The thin clients, instead of querying the database, execute the complex business rules or connect to legacy applications. Different Java EE components are serviced by some containers throughout their life-cycle. We have different types of containers which have described here. Java EE 5 Containers The Java EE 5 containers provide the runtime environment support to the Java EE 5 application components. The Java EE 5 application components use services of the Java EE 5 container throughout their life-cycle. Let’s learn about the different services provided by the Java EE 5 containers to the Java EE 5 application components. Container Services Before the web component, the Enterprise bean or the application client component can be executed; they must be assembled in the Java EE 5 module and deployed into its container. The container manages the services like security, transaction, JNDI lookup, and remote connectivity. Let us explain them all. Security: The Java EE 5 security model allows you to configure the Enterprise bean or the web component so that only the authorized users can be allowed to access the system resources, Transaction: The Java EE 5 transaction model lets you to specify the relationships among the methods that make up a single transaction by which all methods in one transaction are treated as a single unit. G JNDI Lookup: JNDI stands for the Java Naming Directory Interiace. The INDI lookup service provides the interface to the enterprise clients for accessing resources. In local or global JNDI tree , if a Java or web client needs to access the Enterprise bean component running on business tier, then the client can easily access the Enterprise bean by using ihe JNDI lookup service, lookup method finds EJB objects that are bound in JNDI tree. Java EE SRemote Connectivity: Java EE 5 Remote Connectivity model manages the low-level communication between the client and the Enterprise bean, After an Enterprise bean is created, a client invokes methods on it as if it were in the same virtual machine. The question must have arisen in your mind that what are the different types of containers which manage the preceding services? Some non-configurable services are also managed by the Java EE 5 containers, The non-configurable services are like the life-cycles of the Servlets and Enterprise bean. Chapter 1: Introducing EJB Container Types During deployment the Java EE 5 application, components are installed in the Java EE 5 containers. The Fig.EJB-1.2 displays the Java EE 5 server and the Java EE 5 components. As shown in the Fig.EJB-1.2, the Java EE server has two different containers that is Web container and EJB container. Clie Mie Bonne L_] Fig EJB-12 Q Web Container: The Web container handles the execution of the web components such as, Servlet and the JSP pages in the Java EE 5 applications. These web components and their container run on the Java EE 5 server. Q EJB Container: The £)B container handles and takes care of the execution of the Enterprise Java Beans. In addition to these two server-side containers, we have another container which runs on client machine and handles the execution of the application client; this container is known as Application Client Container. After this brief introduction about Java EE specification, its technologies and different containers. Introduction to EJB In today’s era, the human expectations are increasing day by day. Everyone needs the maximum output but at the cost of least effort. Taking the example of real life scenarias, the mode of switching on a television with a button has been switched over to the use of remote control, washing of clothes with hands has come down to the use of washing machines. Similarly, the word enterprise comprises a vast number of transactions like collecting, retrieving, reporting the huge data of a large scale enterprise, But when the developer talks about developing an enterprise application, the entire scenario melts down into a simple word, information. The enterprise applications are defined by their need of retrieving and transforming the bulk information, EJB serves a simpler approach to the enterprise application developers. Enterprise Java Bean is a server-side component that encapsulates the business logic of an application. Business logic processes the data entered by user through web components’ user interfaces of Web application. Enterprise beans are the link between the presentation of your 5 viewed in a Java EE 5 ‘that Java Enterprise and deployed in The technology secure and portable applications Need of EJB Generally, EJB is useful in made by using COBRA transactions and enlarge example to explain scenario has small scale enterprise having days passed, the number of goodwill of the enterprise has business, For expansion, the In other words, the customers database, and can do many level security. So, the owner features which makes it the transactionlly secure Simplicity The application developer does not have to security, transactions, multi-threading, security resource pooling etc. These system-level issues. of EJB architecture. As a result, the developer OQ Reusability The Enterprise bean is a reusable component. It can be * The Enterprise bean which has not yet applications without requiring any changes. = Multiple applications can make calls to the deployed enterprise bean. Q Scalability The EIB applications are highly scalable. Scalability refers to the rate at which an application can be increased, without any degradation of current example, if an application is developed to handle 100 concurrent users with After years, the number of users or the number of customers gets doubled. In to increase the current processing capability of the application, with no performance. a Transactionality Chapter 1: Introducing ETB Developers use transaction concept to provide systems with Atomicity, consistency, isolation and durability properties. These properties finally leaves database of the system at a consistent state if something goes wrong. In EJB, the transaction management is leit to the EJB container which is one of the components of the EJB architecture, Types of Enterprise Beans We have created session bean under EJBClass topic. There are also other types of enterprise Java beans, Various types of beans exist to provide flexibility because each company has different type of distributed system. The Enterprise bean is classified into following types based on functionality: Q_ Session Beans a Entity Beans Q Message-driven beans Session Beans Session beans describe task to be done for a client, They hold usually business processes that have logics or algorithms. Some examples of these business processes are delivering an order, finance calculations etc. The session beans are also non-persistent Enterprise beans. By non- persistence, we mean that the using session bean we cannat provide permanent storage. The session beans can be of two types: O Statetul session Bean Q Stateless cession bean Stateful Session Bean This session bean acts on behalf of a particular client, and maintains the client’s particular information throughout the session. In order to understand it mare clearly, let’s take an example of an Online Banking. Once the online customer logins with the account_id and password, the user can continue with any transaction like amount deposit or withdraw until either the user logs out or the session expires. All transactions will be executed successfully. This is because during the login period of the user, the particular information of its account_id is being maintained across multiple transactions. It exists till the duration of a single client session. So in this way, the Stateful session bean creates a conversational state across multiple method calls and transactions. Stateless Session Bean This session bean does not maintain any conversational state; rather they are pooled by the EIB container to handle multiple requests from multiple clients. In other words, in the case of the single operation, stateless session bean can be used. The single operation can be like mailing, converting the dollars to Rs or depositing an amount in an online bank account, The multiple clients can perform any of the preceding operations simultaneously. The stateless session bean handies multiple client requests, whereas the Stateful session bean takes care of a single client request. EJB 3.0 in Simple Steps Entity Beans The entity beans are the Enterprise bean which contain persistent data and provides persistent storage to that data in a database. By persistence, we mean that the state of the entity bean is saved in a storage mechanism. Persistence can be performed with the help of Java object Serialization and Object Relational Mapping. Second one is latest and currently used technique. Java Object Serialization is done with the help of Serializable interface. It captures the current state of object and saves it into permanent storage. Instead of serializing an object, we can break ‘object into constituent components and store each component separately. For example, Bank account abject is divided into bank account number and account balance components. Each ‘component is stored in two different rows of relational database. The entity bean which manages persistence itself is called Bean Managed Persistence (BMP) entity bean. The entity bean whose persistence is handled by the EJB container is called Container Managed Persistence (CMP) entity bean. Message-Driven Bean A message-driven bean is an Enterprise bean that allows Java EE 5 applications to process messages asynchronously. in other words, the message-driven beans handle operations which do not require immediate response. For example, if a user using a website clicks on the button "keep me informed’, it may call a message-driven bean to add the user to company’s database. Since there is no need for the user to know about the success or failure, so it is an asynchronous message. Previous Versions of EJB ‘We have different versions of EJB which can be used for the application development. The EJB 3.0 was introduced with Java EE 5 specification. Each time a new version of EJB is introduced, some new and significant changes are included. The different previous versions of EJB are EJB 1.0, EJB 1.1, EJB 2.0, and EJB 2.1. The different versions of EJB previous to EJB 3.0 are not being discussed in the book, But to make our reader familiar with the previous architecture and implementation details for EJB, we are explaining EJB 2.1 here before introducing you EJB 3.0. EJB2Z1 The development and implementation of an Enterprise Java Bean requires creation for different multiple interfaces and classes. These interfaces and classes need proper infrastructure to successiully execute business methods. The EJB architecture is the infrastructure or the framework in which the Enterprise bean is being deployed. The EJB architecture can be described with following heads: EJB Server EJB server provides an organized framework for the execution of the applications that are developed by using EIB components. It controls the allocation of the appropriate resources to the applications. In addition, EJB server provides the basis for the EJB container. It provides various system services like naming and transaction service, multiprocessing, security, etc. to the EJB container. Chapter 1: Introducing EJB EJB Container The EJB container that is provided by the EJB server holds instances of more than one EjBs. The EJB container handles life-cycle of the EJB and also provides other container services like transaction, security etc. It serves as an intermediate between the Enterprise bean and the EJB client. The Enterprise bean is deployed in the EJB container, within the EJB server. We have two: interfaces associated with our EJB that is its Home interface and the Remote interface. EJB container automatically generates implementation classes from these Java interfaces and these implementation classes serve as a proxy for the EJB client. The client code invokes a business method on the generated proxies, which in tum places the methad arguments into a message and sends the message to the EJB server. Enterprise Bean The Enterprise bean is the component that is developed by the developer to provide implementation to the business logic, The Enterprise bean is being invoked by the EJB client with the support of the EJB container. The Enterprise bean comprises of two Java interfaces, Home and Remote, and bean implementation class (also known as EJB class), providing Java implementation to the business methods. We will discuss here these one by one. Remote Interface The Remote interface contains the list of the business methods, whose implementation is being provided in the EJB class. In brief, the Remote interface specifies the remote business methods that a client can call on an Enterprise bean. Home interface The Home interface contains methods for finding, creating and removing the EJB instances. EJBHome reference is generated by container from this home interface. EJB Class The EJB class provides implementation ta the business method defined in the Remote interface. It uses EJBHome abjects implicitly ta generate Meta classes. You must have noticed that, to perform a simple task, the developer needs to go through such a lengthy procedure of creating Remote interface, Home interface and the EJB Class, Apart from these, the developer alsa has to create the different configuration files. The Deployment Descriptor is an XML format file containing the information of the Enterprise bean like the name ‘of the Enterprise bean, its type and many more. EJB Client EJB client can be simple Java program or web client. Ultimately, user runs these clients to get results. EJB client program uses JNDI service to use the Enterprise bean in its application. With the help of the JNDI, the client is facilitated with looking up and invocation of the Enterprise bean. So, until the client knows how to lookup and invoke an Enterprise bean, the implementation of the Enterprise bean in its application is not possible. With the help of EJB 2,1, stateless session bean can act as Web service end point and enables EJB container to implement Web service. These session beans may be easily called by using SOAP/HTTP. In earlier versions, Message driven beans use only Java Messaging Service. Now, 9 EJB 3.0 in Simple Steps MDBs can connect to Java EE 5 connector architecture (JCA) message services and also perform messaging by using Java API for XML Messaging (JAXM). EJB 2.1 container also facilitates timer service to schedule callback actions. We use EJBContext to access timer service and EJBContext provides needed general runtime objects to any EJB. Using timer service, we can invoke EJBs at particular time by using event based process. In addition, EJB query language becomes more advanced and includes functions like AVG, SUM, MOD, COUNT, MIN, MAX and ORDER BY, Still the developers found hard creating an application by using EJB 2.1. In order to simplify the task from the developer's point of view, the expert team of EJB came up with EIB 3.0 specification. The new features of £/B3.0 have reduced the complexities for the developers. Need of EJB3.0 Development of EJB applications was not an easy task as it became more complex with each release of EJB specifications. Many developers feel that developing an EJB application is a nightmare. Let’s summarize the complexities of the previous model EJB2.1 here: Q The §JB2.1 and the previous models of EJB required the creation of home and remote interfaces and the implementation of several unnecessary callback methods. This made a lengthy and complex procedure for the Enterprise bean developers to develop a bean. Q The Home and Remote interfaces require implementation of EJBObject and handling many exceptions like CreateExcept ion, RemoteException. The £jB Deployment Descriptor is complex and erroneous. a EJ8 model based on the container managed persistence is again complex to develop and manage. The basic feature of defining a primary key in a standard way using database sequence was not present in EB 2.1. Q Another major complexity of EJBs created using EJB2.x specification is that EJB modules cannot be tested outside an EJB container. Q EJB Client finds difficultly to look up and invoke an EJB. The EJB Client needs to know minute details of JNDI, just to use an EJB in the application. EJB QL is still not so impressive to compel developer to use it. They still use JDBC and SQL or other frameworks like Hibernate for persistence. . New Features of EJB 3.0 The EJB3.0 has addressed these complexities by removing the need of interfaces and Deployment Descriptors, In £JB3.0, these interfaces and the Deployment Descriptors are generated by the EJB container, using metadata annotations. Moreover, the usage of regular Java classes and interfaces has been provided in E]B3.0. We are describing them one by one. Annotations From the developer's point of view, £)B3.0 extensively uses Java annotations. EJB3.0 depends an the annotations. Annotation is a kind of attribute oriented programming. In attribute oriented programming, programmers mark the program elements like classes, methods, to indicate that they maintain applicatian-specific or domain specific semantics. Metadata Annotations are 10 Chapter 1: Introducing EJB specified on the basis of Configuration using Exception approach, Configuration using Exception technique helps in simplifying development in several aspects of EJB 3.0. This technique says that developer writes code only for things where defaults can not be used. For example, some programmers may define a “validate” attribute and associate “validate” attribute with the method implementing the validation. The programmer marks the methad implementing validation with an attribute called “validate”. In this way, the annotation has simplified the EJB development. The annotations are marked with @ symbol and its use is given here: In the preceding code snippet, @remate indicates that it is a remote interface. @ symbol used prior to Remote indicates that it is an annotation. Let’s see how the usage of annotations has made the task simpler for the Enterprise bean developers. In the previous specifications of the EJB, the XML Deployment Descriptor has provided information of an Erterprise bean in the following way: But now in the £/B3.0 architecture, the preceding information of the Enterprise bean can be provided with the help of annotation, like here: In the preceding code snippet, the @Stateless indicates that it is a stateless session bean. So, it’s amazing that there is no need to write Deployment Descriptor to specify properties. The annotations are simpler to use as compared to an XML file. Also vendors like IBM, BEA has introduced annotations for attributes in vendor specific Deployment Descriptor. The inclusion of annotation, as a feature of £]B3.0, has not only simplified the task of Deployment Descriptor but has also simplified the implementation of Callback methods. Callback Methods £JB3.0 has also removed the implementation of unnecessary callback methods like ejbPassivate, ejbActivate, ejbLoad, ejbStore etc. for the EJB developers. Earlier if any type of EJB does not require any of preceding methods, still they need to be implemented in EJB business class. Implementation of these methods now becomes optional. But if developer defines any one of these methods in business class, container will call same method. Also there is one exception in case of removing stateful session bean that is developer needs to use @Remove annotation to remove instance of session bean after invoking business method. Other useful change introduced 1 EJB. 30 in by EJB 3.0 is that any arbitrary method can be designated as a callback method to listen cycle events. For example: In the preceding code snippet, @PreDestroy is the callback annotation. Other annotations comprise of PostConstruct, PrePassivate and Preactivate, Some PostPersist are used specifically for entity beans. These callback annotations are in EJB class or other bean listener class. In second case, we have to specify annotation on bean class to tell container that another bean listener class contains life-cycle callback methods. Dependency Injection 12 The client, to use the constructed bean in its application, needs to know how to invoke that Enterprise bean. The client for an £JB2.1 session bean gets the session bean with JNDI. In order to use an enterprise bean, say Calculator bean, needs to add the following code to locate and invoke one of method: In the preceding code, the JNDI name of the Calculator bean is local/remote instance is obtained with create() method. But in EJB3.0, the JNDI create() method invocation is not required. in E/83.0, a reference to a resource is dependency injection with the @Inject annotation or the @Resource annotation. to container that it is dependent on some resource or another by injection. Entire E/B's context made up of container, resource and environment dependency annotation comprises of type of resource, its properties and its access. In ather words, Dependency annotation is a pattern in which the object creation and the object linking is removed from the object dependency injection, the preceding code gets reduced to: Chapter 1: Introducing EJB calculator cale; In the preceding code, @Inject is the annotation used in order to inject the bean named Calculator. Then the instance named calc is being created of the Calculator bean. In this way, the use of annotations in £)B3.0 has simplified the task of both developers and the E|BClient. Some other examples of dependency annotations are as follows: GEIB) (name="SessionBeanName", beanInterface=sessionseaninterface.class) gs @Resource (name="Database", type="javax.sq].Datasource.class") EJB annolation injects stubs of session bean having name SessionBeanName. The @Resource annotation used to inject service object having INDI name *Database’. This name is present in either global or local JNDI tree. Dependency annotations may be associated to bean class, its member variables or methods, Information to be specified in them depends upon the context and the amount of data to be fetched from that context. This model states that interfaces are not compulsory for entity beans but they are necessary for session and message driven beans. This line does not convey to developer to define interface for session and message driven beans but it means that a bean interface will be generated of type or remote according to the annotation used in bean class. Sometimes you do not like to access 0 some methods in EJB in the interface. Then in this case, you can create your own bean interface and does not rely upon generated bean interface as it exposes all methods. of Home Interface ana Home ubjects removed the unnecessary requirement of the home interface. The Home interfaces the home objects have been replaced by the POJO's and PO)!'s. The POJO's stands for Plain Java Objects and PO}I’s stands for Plain Old Java Interfaces. Simple Java Bean is called and simple Java interface is called POJI. Previously, when we created a calculator bean, we had created a Home interface named CalculatorHome. But now in EJB3.0, interface has been removed and the same code gets simplified as follows: notice that no Home interface is being defined for the Enterprise bean. The implementation javax.ejb.SessionBean has also been removed due the usage of the annotation @Stateless. class can be annotated by using some other @Stateful, @MessageDriven or @Entity 13 EB in Simple Steps Elimination of Component Interface Moreover the business or component interlace becomes Plain Old Java Interface. E)B3.0 has eliminated the Component interface. The E)BObject/E|BLocalObject and the Remote Exceptions which needs to be imported in EJB 2.1 to make component interface have also been removed. Component interface needs to be local or remote which all depends on where business class is located. Rather, now the POJI that is Plain Old Java Interface serves as a business interface supporting either remote ar local access. The Remote interface which was in EJB2.x has now been removed. The Plain Old Java Interface has been introduced. The code snippet for the Plain Old Java Interface is as follows: Now @Remote is annotation to generate component interface that is of remote type. As a whole, EJB 3.0 eliminates the requirement of E}B Component interfaces. EJB3.0 has incorporated the use of POJ!'s for session beans. Interceptors Interceptors are methads which intercept business method calls or lifecycle callback calls. We can use interceptors with session beans and message-driven beans. Alternatively, we define interceptor methods inside a separate class called interceptor class, Interceptors provide us way to enhance business methods with extra functionality. For example, Validation of parameters to be passed ta business method can be done by using interceptor methods. More than one interceptor can be invoked on one EJB in the form of chain. We use @Interceptors annotation to import chain of interceptors associated with the bean. We can define interceptor methods using, @Aroundinvoke annotation. Following code is used to add interceptor methods to bean: StringServiceBean session bean is of stateful type and intercepts methods of MethodProfiler interceptor class. The name of the generated remote interface far this session bean is StringServiceRemote. dava Persistence AP} The Enterprise applications have a need to collect vast amount of information. The long term storage of this vast information has been simplified by Java Persistence API. The first release of Java EE 5 introduced entity bean as a solution to java Persistence. The introduction of the entity bean has prevented the developers to directly deal with the persistence. But the first release of 14 Chapter 1: Introducing EJB the technology lacked many features and provoked many problems to the developers. Some of the major problems were like relationships of the entities which had to be managed by the applications, foreign key fields were required to be stored and managed on the bean class. The EJB2.1 specification solved many of the problems by introducing the idea of container managed entity beans. In the container managed entity bean, the server was responsible for generating subclass to manage the persistent data. This EJB2.1 specification also introduced the Enterprise Java Bean Query Language (EJBQU). £/BQL is a query language designed to create queries for ‘CMP entity beans. It is similar to SQL but searches for persistent attributes of enterprise Java bean. EJB2.1 specification, despite of providing improvements, was still overloaded with the major problems and complexities. The £B3.0 provides new java Persistence API, which simplifies the programming model for entity persistence. Now Object Relational Mapping or Persistence approach uses POJO model instead of abstract persistence schema model. This mapping used to map entities and their relationships to application’s database. EJB 3.0 entily depicts persistent mation stored in database using Container Managed Persistence (CMP) but EJB 2.1 ent bean only represents persistent information stored in database. The optimistic locking technique only supported by TopLink persistence framework is also encapsulated in EJB 3.0 specification, It also enhances RAW access ratios, This locking allow to use objects in disconnected mode! which means changing data and their relationships offline and merge data Operations into one transaction. Optimistic lock walue tells us changed capy of data is not stale. We can also create deep and wide entity inheritance hierarchies. Other additions and subtractions made in the Java Persistence API, which were not there in £JB2.1, are as follows: 2 It requires less number of classes and interfaces. Q New EntityManager API similar to Hibernate is introduced to perform operations like creation, removal and searching on entity beans The lengthy Deployment Descriptors have been eli It provides cleaner, easier and standardized object-relational mapping. The need for lookup code has also been eliminated. It adds support for inheritance, polymorphism, and polymorphic queries. Itadds support for named (static) and dynamic queries. We can now perform many database related operations instead of only one operation generating primary key in EJB 2.1. It provides a Java Persistence query language—an enhanced E|B QL. It makes easier to test entities without the EJB container. Farlier, developers need to be aware of deployment platform to test EJBs. The crux of the new Java Persistence API has been listed earlier. In detail, it would be explained in the later chapters, ated through annotations. oocooooc a Summary This chapter starts from structure of enterprise applications and describes Java EE 5 platform which is used to develop these enterprise applications. It introduces Java EE’s components like 15 EJB 3.0 in Simple Steps Servlets, JSP and EJB and its all types of containers with their services. It also discusses requirements. for introducing EJB technology. We have also discussed EIB 2.1, its features, various types of Enterprise beans and EJB 2.1 limitations. Finally, we have explained you to how latest version 3.0 of EJB overcome limitations of EJB 2.1 with its new features like annotations, dependency injections , POJO tehniques and simplifies all aspects of development, In next chapter, we will take you to the development of session beans in EJB 3.0. 16 Urheberrechthch geschitztes Bild Urheberrechilich geschiltztes Material EJB 3.0in Introduction Before getting into to the details of session bean in this chapter, let's first discuss about what bean? You must have heard of the term ‘Java Bean’ in Java. In a simple words, Bean can defined as one of the reusable software component, and a number of beans can be together to form an application. A JavaBean is a regular Java class that has setters and methods to provide access to its state and EJB is a regular Java class that has a method lagic inside it and provides a remote interface to achieve the bean logic and the home which actually creates the Bean, JavaBeans are the non-sharable components that developed and run within a single system, whereas EJB is used in a distributed environment can be shared across system. The main focus of this book is on EJB; so, let's go for a discussion regarding EJB. The enterprise level applications are entirely based upon the business logic and according concept, the term EJB is also related to business logic, In the previous chapter, we have discussed the concept of EJB and different types of EJB i.e. Session bean, Entity bean Message-driven bean. Here, in this chapter, we are going to discuss the concept of in detail with its full implementation through examples. Concept of Session Bean The term Session bean has coined using two words i.e session and bean. The that the bean instance is available for a particular duration of a unit of work and it after that which means that its lifetime is within a specific duration. A Session defined as the reusable componert, thr? contict o# toric far tho business process and works on behalf of the client code wnicn invokes it. 50, a session bean represents a single inside the Application server which: Q Does not maintain the state of client. Q Does not represent the data in data store. Session bean is not persistent and hence it lives for a short period and ends-up its life server stops. Now the question comes- when to use the session beans? Session beans are suited for the business process or for the control logic that exhibits multiple entity beans reflects from the Fig.£JB-2.1 also. Fig EJB-21 18

You might also like