Sunteți pe pagina 1din 52

As discussed below, the EJB architecture specifies three types of beans - session beans, entity beans, and message-driven

beans. A bean developer has to specify the home and remote interfaces and also he has to implement one of these bean interfaces depending upon the type of the bean. For instance, for session beans, he has to implement the javax.ejb.SessionBean interface. The EJB architecture expects him to implement the methods specified in the bean interface and the methods specified in the home and remote interfaces. During the deployment time, he should specify the home and remote interfaces and bean implementation class to define a bean. The EJB container relies on specific method names and uses delegation for invoking methods on bean instances.

Thus regarding the first requirement, the EJB container generates the proxy objects for all beans. For the second one, the EJB container for each bean implement a proxy object to the home interface and publishes in the JNDI implementation of the J2EE platform. One can use JNDI to look for this and obtain a reference. As this object implements the home interface only, he can use one of the creation methods of the home object to get a proxy to the remote interface of the bean. When one invokes a creation method on the home proxy object, the container makes sure that a bean instance is created on the EJB container runtime and its

proxy is returned to the client. Once the client gets hold of the proxy for the remote interface, it can directly access the services of the bean.

Finally, once the client decides to stop accessing the services of the bean, it can inform the EJB container by calling a remote method on the bean. This signals the EJB container to disassociate the bean instance from the proxy and that bean instance is ready to service any other clients.

Types of EJBs

The EJB architecture is based on the concept that in an enterprise computing system, database persistence-related logic should be independent of the business logic that relies on the data. This happens to be a very useful technique for separating business logic concerns from database concerns. This makes that business logic can deal with the business data without worrying about how the data is stored in a relational database.

Enterprise JavaBeans server-side components come in two fundamentally different types: entity beans and session beans.

Basically entity beans model business concepts that can be expressed as nouns. For example, an entity bean might represent a customer, a piece of equipment, an item in inventory. Thus

entity beans model real-world objects. These objects are usually persistent records in some kind of database.

Session beans are for managing processes or tasks. A session bean is mainly for coordinating particular kinds of activities. That is, session beans are plain remote objects meant for abstracting business logic. The activity that a session bean represents is fundamentally transient. A session bean does not represent anything in a database, but it can access the database.

Thus an entity bean has persistent state whereas a session bean models interactions but does not have persistent state.

Session beans are transaction-aware. In a distributed component environment, managing transactions across several components mandates distributed transaction processing. The EJB architecture allows the container to manage transactions declaratively. This mechanism lets a bean developer to specify transactions across bean methods. Session beans are client-specific. That is, session bean instances on the server side are specific to the client that created them on the client side. This eliminates the need for the developer to deal with multiple threading and concurrency.

Unlike session beans, entity beans have a client-independent identity. This is because an entity bean encapsulates persistent data. The EJB architecture lets a developer to register a primary key class to encapsulate the minimal set of attributes required to represent the identity of an entity bean. Clients can use these primary key objects to accomplish the database operations, such as create, locate, or delete entity beans. Since entity beans represent persistent state, entity beans can be shared across different clients. Similar to session beans, entity beans are also transactional, except for the fact that bean instances are not allowed to programmatically control transactions.

These two types of beans are meant for synchronous invocation. That is, when a client invokes a method on one of the above types, the client thread will be blocked till the EJB container completes executing the method on the bean instance. Also these beans are unable to service the messages which comes asynchronously over a messaging service such as JMS. To overcome this deficiency, the EJB architecture has introduced a third type of bean called message-driven bean. A message-driven bean is a bean instance that can listen to messages from the JMS.

Unlike other types of beans, a message-driven bean is a local object without home and remote interfaces. In a J2EE platform, message-driven beans are registered against JMS destinations.

When a JMS message receives a destination, the EJB container invokes the associated message-driven bean. Thus message-driven beans do not require home and remote interfaces as instances of these beans are created based on receipt of JMS messages. This is an asynchronous activity and does not involve clients directly. The main purpose of messagedriven beans is to implement business logic in response to JMS messages. For instance, take a B2B e-commerce application receiving a purchase order via a JMS message as an XML document. On receipt of such a message in order to persist this data and perform any business logic, one can implement a message-driven bean and associate it with the corresponding JMS destination. Also these beans are completely decoupled from the clients that send messages.

Session Beans: Stateful and Stateless

Session beans can be either stateful or stateless. Stateful session beans maintain conversational state when used by a client. Conversational state is not written to a database but can store some state in private variables during one method call and a subsequent method call can rely on this state. Maintaining a conversational state allows a client to carry on a conversation with a bean. As each method on the bean is invoked, the state of the session bean may change and that change can affect subsequent method calls.

Stateless session beans do not maintain any conversational state. Each method is completely independent and uses only data passed in its parameters. One can specify whether a bean is stateful or not in the bean's deployment descriptor.

Entity Beans: Container and Bean Managed Persistence

An example entity bean in a B2B application is given as follows. A purchase order is a business identity and requires persistence store such as a relational database. The various purchase order attributes can be defined as the attributes of an entity bean. Since database operations involve create, update, load, delete, and find operations, the EJB architecture requires entity beans to implement these operations. Entity beans should implement the javax.ejb.EntityBean interface that specifies the load and delete operations among others. In addition, the bean developer should specify the appropriate create and find methods on the home interface, and provide their implementation in an entity bean.

There are two types of entity beans and they are distinguished by how they manage persistence. Container-managed beans have their persistence automatically managed by the EJB container. This is a more sophisticated approach and here the bean developer does not implement the persistence logic. The developer relies on the deployment descriptor to specify attributes whose persistence should be managed by the container. The container knows how a

bean instance's fields map to the database and automatically takes care of inserting, updating, and deleting the data associated with entities in the database.

Beans using bean-managed persistence do all this work explicitly: the bean developer has to write the code to manipulate the database. The EJB container tells the bean instance when it is safe to insert, update, and delete its data from the database, but it provides no other help. The bean instance has to do the persistence work itself.

EJB Container: The environment that surrounds the beans on the EJB server is often referred to as the container. The container acts as an intermediary between the bean class and the EJB server. The container manages the EJB objects and EJB homes for a particular type of bean and helps these constructs to manage bean resources and apply the primary services relevant to distributed systems to bean instances at run time. An EJB server can have more than one container and each container in turn can accommodate more than one enterprise bean.

Remote Interface: This interface for an enterprise bean defines the enterprise bean's business methods that clients for this bean can access. The remote interface extends javax.ejb.EJBObject, which in turn extends java.rmi.Remote.

Home interface: This interface defines the bean's life cycle methods such as creation of new beans, removal of beans, and locating beans. The home interface extends javax.ejb.EJBHome, which in turn extends java.rmi.Remote.

Bean Class: This class has to implement the bean's business methods in the remote interface apart from some other callback methods. An entity bean must implement javax.ejb.EntityBean and a session bean must implement javax.ejb.SessionBean. Both EntityBean and Session Bean extend javax.ejb.EnterpriseBean.

Primary Key: This is a very simple class that provides a reference into the database. This class has to implement java.io.Serializable. Only entity beans need a primary key.

Deployment Descriptors: Much of the information about how beans are managed at runtime is not supplied in the interfaces and classes mentioned above. There are some common primary services related with distributed systems apart from some specific services such as security, transactions, naming that are being handled automatically by EJB server. But still EJB server needs to know beforehand how to apply the primary services to each bean class at runtime. Deployment descriptors exactly do this all important task.

JAR Files: Jar files are ZIP files that are used specifically for packaging Java classes that are ready to be used in some type of application. A Jar file containing one or more enterprise beans includes the bean classes, remote interfaces, home interfaces, and primary keys for each bean. It also contains one deployment descriptor.

Deployment is the process of reading the bean's JAR file, changing or adding properties to the deployment descriptor, mapping the bean to the database, defining access control in the security domain, and generating vendor-specific classes needed to support the bean in the EJB environment. Every EJB server product comes with its own deployment tools containing a graphical user interface and a set of command-line programs.

For clients like enterprise bean itself, Java RMI or CORBA client, to locate enterprise beans on the net, Java EJB specifications specify the clients to use Java Naming and Directory Interface (JNDI). JNDI is a standard Java extension that provides a uniform Application Programming Interface (API) for accessing a wide range of naming and directory services. The communication protocol may be Java RMI-IIOP or CORBA's IIOP

There are some special integrated application development tools such as Inprise's JBuilder, Sun's Forte and IBM's VisualAge, for designing EJBs in the market.

Why EJB (Enterprise Java Beans)?

Enterprise Java Beans or EJB for short is the server-side component architecture for the Java 2 Platform, Enterprise Edition (J2EE) platform. EJB technology enables rapid and simplified development of distributed, transactional, secure and portable applications based on Java technology. Sun Microsystems in the beginning put forward Java Remote Method Invocation (RMI) API as a distributed object computing technology. RMI specifies how to write objects so that they can talk to each other no matter where on the network they are found. At its core, however, RMI is nothing more than an API to which our distributed objects must conform. RMI says nothing about about other characteristics normally required of an enterprise-class distributed environment. For example, it does not say anything about how a client might perform a search for RMI objects matching some criteria. It also does not specify how those distributed objects work together to construct a single transaction. Thus there is a realization for a need of a distributed component model. A component model is a standard that defines how components are written so that systems can be built from components by different developers with little or no customization. There is already a component model called as JavaBeans in Java. It is a component model that defines how we write user interface components so that they may be plugged into third-party applications. The magic thing about JavaBeans is that there is very little API behind the specification; we neither implement nor extend any special classes and we need not call any special methods. Enterprise JavaBeans is a more complex extension of this concept. While there are API elements behind Enterprise JavaBeans, it is more than an API. It is a standard way of writing distributed components so that the written components can be used with the components we write in someone else's system. RMI does not support this ability for several reasons listed below. Here comes the features that are not available with RMI. 1. Security - RMI does not worry about security. RMI alone basically leaves our system wide open. Any one who has access to our RMI interfaces can forge access to the underlying objects. If we do not impose complex security restrictions to authenticate clients and verify access by writing extra code, we will have no security at all. Thus our components are therefore unlikely to interoperate with other's components unless we agree to some sort of security model. 2. Searching - RMI provides the ability to do a lookup only for a specific, registry-bound object. It specifies nothing about how we find unbound objects or perform searches for a group of objects meeting certain

requirements. For example, writing a banking application, we might want to support the ability to find all accounts with negative balances. In order to do this in an RMI environment, we would have to write our own search methods in bound objects. Our custom approach to handling searches will not work with someone's else custom approach to searching without forcing clients to deal with both search models. 3. Transactions - The most important feature for a distributed component model is transactions. RMI does not support transactions. If we develop an RMI-based application, we need to address how we will support transactions. That is, we need to keep track of when a client begins a transaction, what RMI objects that client changes, and commit and roll back those changes when the client is done. This is further compounded by the fact that most distributed object systems support more than one client at a time. Different transaction models are much more incompatible than different searching or security models. While client coders can get around differences in search and security models by being aware of those differences, transaction models can almost never be made to work together. 4. Persistence - RMI does not care about how RMI objects persist across time. There is a persistence utility that supports saving RMI objects to a database using JDBC. But it is very difficult to integrate with RMI objects designed to use some other persistence model because the other persistence model may have different persistence requirements. Enterprise JavaBeans addresses all of these points so that we can literally pick and choose the best designed business components from different vendors and make them work and play well with one another in the same environment. EJB is now the standard component model for capturing distributed business components. It hides from us the details we might have to worry about ourself if we were writing an RMI application.

Introduction To Java Beans


J2EE specification defines the structure of a J2EE application. According to the specification J2EE application consists of two components, web component and the enterprise bean. Web component consists of all the programs and the files used to provide the user interface and these may contain JSP, Servlets, images, html files etc. These files are archived into .war file and deployed on the web server. Enterprise Bean consists of all the program necessary to provide the business to the application. These files are archived into .jar file and are deployed on the application server such as WebLogic 6.0.

You can deploy the web component and the ejb components separately on the web server and the application server respectively. J2EE specification also provide a way to package these files into one archive .ear file and then deploy on the server.

Writing and deploying the web component


In this section we are going to describe you how to write and deploy the web component on the WebLogic 6.0 web server. Web component follows the standard directory structure defined in the J2EE specification.

Directory Structure of Web Component /


index.htm, JSP, Images etc.. Web-inf
web.xml

classes
servlet classes

lib
jar files

Root directory of the web archive ('.war' file) contains all the html, jsp, images files and the additional directories containing these files. In the root directory there is a special directory 'Web-inf' which contains the web deployment descriptor (web.xml), classes and the lib directory.

To download the code for this lesson click here. To deploy this web component download the code and then extract it in you favorite directory. One directory will be created with the name of lesson1, go to the leson1 directory and to create the war file issue the following command from dos prompt:
c:\mydir\lesson1>

jar cf lesson1.war *

Web component file with the name of lesson1.war will be created. You can deploy it to the WebLogic 6.0 server using console. After deploying it using the WebLogic 6.0's console type http://localhost:7001/lesson1/ to view. Server will serve index.jsp to your browser. Now let's see the web.xml file which describes the content of the web component. Here is the content of web.xml file. <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <welcome-file> index.jsp </welcome-file> <session-config> <session-timeout>54</session-timeout> </session-config>

</web-app>
web.xml file start with xml declaration and after the document type declaration <web-app> tag starts. All the information regarding the content of the .war file are written between <web-app> and </web-app> tags in the xml format. In the first lesson we are setting index.jsp as our welcome page and the following lines of the web.xml file is used to accomplish this.

<welcome-file> index.jsp </welcome-file> and the following code sets the session time: <session-config> <session-timeout>54</session-timeout> </session-config> To learn more about writing the web.xml file and deploying the web application on WebLogic 6.0 please visit:

http://e-docs.bea.com/wls/docs60/adminguide/config_web_app.html
In the next lesson we will write stateless session bean and then deploy on the WebLogic 6.0 Server.

Writing Session bean


In this lesson you will learn how to develop Hello World Session Bean. We will use ant to build the application. Our application will be deployed on the Web Logic Application for testing. What is Session Bean? Session is one of the EJBs and it represents a single client inside the Application Server. Stateless session is easy to develop and its efficient. As compare to entity beans session beans require few server resources. A session bean is similar to an interactive session and is not shared; it can have only one client, in the same way that an interactive session can have only one user. A session bean is not persistent and it is destroyed once the session terminates. Session Bean Types Session Beans are of two types, Stateful Session Bean and Stateless Session Bean. Stateless Session Beans A stateless session bean does not maintain a conversational state for the client. When a client invokes the method of a stateless bean, the bean's instance variables may contain a state, but only for the duration of the invocation.

Because stateless session beans can support multiple clients, they can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients. Stateful Session Beans The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client-bean session. Because the client interacts ("talks") with its bean, this state is often called the conversational state. Writing Stateful Session Bean A Session Bean is composed of the following parts:

Remote Interface: The Remote Interface is the client view of the bean. Home Interface: The Home Interface contains all the methods for the bean life cycle (creation, suppression) used by the client application. Bean Class: The bean implementation class implements the business methods. Deployment Descriptor: The deployment descriptor contains the bean properties that can be edited at assembly or deployment time.

Steps involved in developing the Stateful Session Bean can be summarized in following steps: 1. 2. 3. 4. 5. Define Home Interface Define Remote Interface Develop EJB class Write deployment descriptors Package, deploy and test the application

Define Home Interface The Session bean's home interface defines one or more create(...) methods and each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. The return type of a create method is the Bean's remote interface type. In case of Stateless Session Bean there is one create method with no arguments. A remote home interface extends the javax.ejb.EJBHome interface, while a local home interface extends thejavax.ejb.EJBLocalHome interface. Here is the source code of our home interface:

/* * TestSessionBeanHome.java */ package examples; /** * Home interface for TestSessionBean. * @author Deepak Kumar * @Web http://www.roseindia.net * @Email deepak@roseindia.net */ public interface TestSessionBeanHome extends javax.ejb.EJBHome { public examples.TestSessionBean create() throws javax.ejb.CreateException, java.rmi.RemoteException; }

Define Remote Interface As mentioned earlier, Remote Interface is the client view of the bean and the functions defined in the remote interface is visible to the client. There should be an implementation in the Bean class for the all the functions defined in the remote interface. Here is the source code of our Remote Interface:

/* * TestSessionBean.java * */ package examples; /** * Remote interface for TestSessionBean. * @author Deepak Kumar * @Web http://www.roseindia.net * @Email deepak@roseindia.net */ public interface TestSessionBean extends javax.ejb.EJBObject { /** * The method that returns Hello Message */ public java.lang.String SayHello( ) throws java.rmi.RemoteException; }

Define Enterprise Bean Class In the EJB class we write all the business methods along with required that is necessary to implement. In the EJB class methods are defined public. The Session Bean interface methods that the EJB provider must must be defined in the Session bean class are:

public void setSessionContext(SessionContext ic); This method is used by the container to pass a reference to the SessionContext to the bean instance. public void ejbRemove(); This method is invoked by the container when the instance is in the process of being removed by the container.

public void ejbPassivate(); This method is invoked by the container when it wants to passivate the instance. public voidejbActivate(); This method is invoked by the container when the instance has just been reactivated.

A stateful session Bean with container-managed transaction demarcation can optionally also implements the javax.ejb.SessionSynchronization interface.

The Session Synchronization interface methods that must be developed are:

public void afterBegin(); This method notifies a session Bean instance that a new transaction has started. public void afterCompletion(boolean committed); This method notifies a session Bean instance that a transaction commit protocol has completed and tells the instance whether the transaction has been committed or rolled back.

public void beforeCompletion(); This method notifies a session Bean instance that a transaction is about to be committed.

Here is the source code of our Session Bean class:

/* * SessionBean.java * */ package examples; import import import import import java.rmi.RemoteException; javax.ejb.CreateException; javax.ejb.EJBException; javax.ejb.SessionBean; javax.ejb.SessionContext;

/** * @author Deepak Kumar * @Web http://www.roseindia.net * @Email deepak@roseindia.net */ public class MyTestSessionBean implements SessionBean{ public void ejbCreate() throws CreateException { } public void setSessionContext( SessionContext aContext ) throws EJBException { } public void ejbActivate() throws EJBException { } public void ejbPassivate() throws EJBException { } public void ejbRemove() throws EJBException { } /** * The method that returns Hello Message * */ public String SayHello(){ String msg="Hello! I am Session Bean"; System.out.println(msg); return msg; } }

In the next lesson we will write the deployment descriptors and the servlet to test the Hello World Session bean.

Session Beans

What is a Session bean

A session bean is the enterprise bean that directly interact with the user and contains the business logic of the enterprise application. A session bean represents a single client accessing the enterprise application deployed on the server by invoking its method. An application may contain multiple sessions depending upon the number of users accessing to the application. A session bean makes an interactive session only for a single client and shields that client from complexities just by executing the business task on server side. For example, whenever a client wants to perform any of these actions such as making a reservation or validating a credit card, a session bean should be used. The session bean decides what data is to be modified. Typically, the session bean uses an entity bean to access or modify data. They implement business logic, business rules, algorithms, and work flows. Session beans are relatively short-lived components. The EJB container may destroy a session bean if its client times out. A session bean can neither be shared nor can persist (means its value can not be saved to the database) its value. A session bean can have only one client. As long as the client terminates, session bean associated with this client is also terminated and the data associated with this bean is also destroyed.

The above figure shows how Session Bean interacts with the clients as well as with the Entity Beans. Session beans are divided into two parts.

Stateless Session Beans: A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the instance of bean variables may contain a state specific to that client only for the duration of a method invocation. Once the method is finished, the clientspecific state should not be retained i.e. the EJB container destroys a stateless session bean. These types of session beans do not use the class variables (instance variables). So they do not persist data across method invocation and therefore there is no need to passivates the bean's instance. Because stateless session beans can support multiple clients, they provide the better scalability for applications that require large numbers of clients.

Stateful Session Beans: These types of beans use the instance variables that allows the data persistent across method invocation because the instance variables allow persistence of data across method invocation. The client sets the data to these variables which he wants to persist. A stateful session bean retains its state across multiple method invocations made by the same client. If the stateful session bean's state is changed during a method invocation, then that state will be available to the same client on the following invocation. The state of a client bean is retained for the duration of the client-bean session. Once the client removes the bean or terminates, the session ends and the state disappears. Because the client interacts with its bean, this state is often called theconversational state.

For example, consider a customer using a debit card at an ATM machine. The ATM could perform various operations like checking an account balance, transferring funds, or making a withdrawal. These operations could be performed one by one, by the same customer. So the bean needs to keep track its state for each of these operations to the same client. Thus Stateful session beans has the extra overhead for the server to maintain the state than the stateless session bean. The user interface calls methods of session beans if the user wants to use the functionality of the session bean. Session beans can call to other session beans and entity beans. When to use session beans:

Generally session beans are used in the following circumstances:

When there is only one client is accessing the beans instance at a given time. When the bean is not persistent that means the bean is going to exist no longer. The bean is implementing the web services.

Stateful session beans are useful in the following circumstances:

What the bean wants to holds information about the client across method invocation. When the bean works as the mediator between the client and the other component of the application. When the bean have to manage the work flow of several other enterprise beans.

Stateless session beans are appropriate in the circumstances illustrated below:

If the bean does not contain the data for a specific client. If there is only one method invocation among all the clients to perform the generic task.

Life Cycle of a Stateless Session Bean: Since the Stateless session bean does not passivates across method calls therefore a stateless session bean includes only two stages. Whether it does not exist or ready for method invocation. A stateless session bean starts its life cycle when the client first obtains the reference of the session bean. For this, the container performs the dependency injection before invoking the annotated@PreConstruct method if any exists. After invoking the annotated @PreConstruct method the bean will be ready to invoke its method by the client.

The above figure demonstrates how the Stateless Session Beans are created and destroyed. The container calls the annotated @PreDestroy method while ending the life cycle of the session bean. After this, the bean is ready for garbage collection. Life Cycle of a Stateful Session Bean: A Stateful session bean starts its life cycle when the client first gets the reference of a stateful session bean. Before invoking the method annotated @PostConstruct the container performs any dependency injection after this the bean is ready. The container may deactivate a bean while in ready state (Generally the container uses the least recently use algorithm to passivates a bean). In the passivate mechanism the bean moves from memory to secondary memory. The container invokes the annotated@PrePassivate method before

passivating the bean. If a client invokes a business method on the passivated bean then the container invokes the annotated @PostActivate method to let come the bean in the ready state.

The above image shows the various states of the Stateful Session Beans

While ending the life cycle of the bean, the client calls the annotated @Remove method after this the container calls the annotated @PreDestroy method which results in the bean to be ready for the garbage collection.

Understanding Stateful and Stateless Session Bean Life Cycle

In this section of EJB tutorial, we will learn about the lifecycle of Stateful and Stateless Session Beans. Stateless Session Bean Life cycle There are two stages in the Lifecycle of Stateless Session Bean. These are:

a) Does Not Exist In the Does Not Exist stage, bean does not have instance in the memory. In this stage bean has not been instantiated. b) Method Ready Pool In the Method Ready Pool stage bean has instance(s) in the memory of the EJB container and it is ready to serve clients. On the startup of the EJB container some instances of the bean are created and placed in the pool. EJB container creates the new instance of the Bean and then sets the session context (setSessioncontext()) and it calls the ejbCreate() method to place the bean in the Method Ready Pool stage. Container calls the ejbRemove() method to move the bean into Does Not Exist state. Following Diagram shows the Life cycle of Stateless Session Bean

Stateful Session Bean Life cycle There are there stages in the life cycle of Stateful Session bean Life cycle. These are: a) Does Not Exist This is the Does Not Exist stage, bean does not have instance in the memory. In this stage bean has not been instantiated. b) Method Ready Pool In the Method Ready Pool stage bean has instance in the memory of the EJB container and it is ready to serve client. One instance of the Stateful Session Bean servers only one client. When Client Calls create(args) method on the Home Interface, server creates new instance of the bean and sets the Session Context and then

container calls the ejbCreate(args) method on the bean and places the bean into Method Ready Pool stage. ejbRemove or Timeout moves the bean into Does Not Exist stage. c) Passive state In the Passive state the bean is passivated to conserve the resource. The passivate method is called before the instance enters the "passive" state. The instance should release any resources that it can re-acquire later in the ejbActivate() method. After the passivate method completes, the instance must be in a state that allows the container to use the Java Serialization protocol to externalize and store away the instance's state. ejbRemove or Timeout moves the bean into Does Not Exist stage. Following Diagram shows the Life cycle of Statelful Session Bean

Java Persistence API

Java Persistence API is the standard API used for the management of the persistent data and object/relational mapping. Java Persistence API is added in Java EE 5 platform. Every application server compatible with Java EE 5 supports the Java Persistent APIs. Java Persistence API ensures the management of persistence and object/relational mapping. These are helpful while using the JPA in the development of applications using the platform for Java EE 5. It provides O-R mapping facility to manage relational data in java application. The Java Persistence API contains the following areas:

Java Persistence API O-R mapping metadata The query language

Features of JPA: Java Persistence API is a lightweight framework based on POJO for object-relational mapping. Java language metadata annotations and/or XML deployment descriptor is used for the mapping between Java objects and a relational database. It allows the SQL-like query language that works for both static as well as dynamic queries. It also allows the use of the pluggable persistence API. Java Persistence APIs are mainly depends on metadata annotations. API includes:

Java Persistence API Metadata annotations Java Persistence query language

Advantages of JPA: Java Persistence API is build upon the best ideas from the persistence technologies like TopLink, JDO and Hibernate. Java Persistence API is compatible with Java SE environment as well as Java EE and allows developers to take advantages of the standard persistence API. Persistency of data is not so easy for most of the enterprise applications because for this they require access to the relational database like Oracle 10g. It is your responsibility to update and retrieve the database by writing the code using SQL and JDBC. While several object-relational (O-R) frameworks such as JBoss Hibernate and OracleTopLink make persistence challenges simpler and became popular. They let the java developer free from writing JDBC code and to concentrate only on the business logic. In EJB 2.x, container manage persistence (CMP) try to solve the persistence challenges but not successful completely. Persistence tier of the application can be developed in several ways but Java platform does not follow any standard that can be used by both Java EE and Java SE environment. But the Java Persistence API (JPA) part of EJB 3.0 spec (JSR-220) makes the persistence API standard for the Java platform. O/R mapping vendors like Hibernate and TopLink as well as JDO vendors and other leading application server vendors are receiving the JSR-220. Here we are describing EJB3 JPA by using the simple domain object model by an example. Working process of an EJB application using JPA:

Domain Model: While developing an enterprise application, first design the domain object model required to persist the data in the database. Domain model represents the persistence objects or entities in the database. An entity represents a row in the data. An entity may be a person, place or a thing about which you want to store the data in the database. A rich domain model includes the characteristics of all the object oriented behavior like inheritance, polymorphism and many more. While developing an enterprise application, first design the domain object model to persist the data in the database then design the database schema with the help of database designer. The figure illustrated below shows the bi-directional one-to-many relationship between the Employee and Department. The Contractor and the fulltime entities are inherited from the entity Employee.

Sample domain object model The Basics of EJB3 JPA and O-R Mapping Framework: Each of the O-R mapping framework such as Oracle TopLink provides three facilities:

1.

It defines a declarative way known as O-R mapping metadata to perform O-R mapping. Most of the framework use XML to store the O-R mapping metadata.

2.

An API is required to manipulate like to perform CRUD (CRUD stands for create, read, update, and delete) operations. The API allows you to persist, remove, update or retrieve the object from the database. O-R framework performs operations using the API and the O-R mapping metadata on your behalf.

3.

Use of a query language for retrieving objects from the database is the proper way since improper SQL statements may result in slow down the performance of the operation performing on the database. A query language allows to retrieve the entities from the database and spares you from writing the SQL SELECT statements.

EJB 3 provides a standard way to use the persistence by providing a standard O-R mapping mechanism, a way to extend EJB-QL to retrieve entities and an EntityManager API to perform CRUD operations. EJB3 Java Persistence API (JPA) standardizes the use of persistence for the Java platform by providing a standard mechanism for O-R mapping, an EntityManager API to perform CRUD operations, and a way to extend EJB-QL to retrieve entities. I'll discuss these three aspects of JPA later. Metadata Annotation in Action: Metadata annotations are first time introduced in Java SE 5.0. To make the development easy all the components of Java EE including EJB3 uses the metadata annotations. In EJB3 JPA annotation defines the objects, O-R mappings, and the relationships among them. JPA also have another option to use XML descriptor, But use of the metadata annotations make the development simpler and more efficient. Entities: An entity can be considered as a light weight persistence domain object. An entity defines a table in a relational database and each instance of an entity corresponds to a row in that table. An entity refers to a logical collection of data that can be stored or retrieved as a whole. For example, in a banking application, Customer and BankAccount can be treated as entities. Customer name, customer address etc can be logically grouped together for representing a Customer entity. Similarly account number, total balance etc may be logically grouped under BankAccount entity. Persistence fields or persistent properties defines the persistent state of an entity. To map the entities and their relationship to the data in the relational database these entities use the object-relational mapping. Requirements of Entity Classes: There are some requirements that an entity must follow:

The class must contain either a public or a protect no argument constructor, while it can contain other constructors. The class as well as methods and persistence instance variables must not be declared as final. Use the annotation javax.persistence.Entity to annotate the class. Declare the persistence instance variables as protected, private or package-private so that they can directly accessed only by the entity class's methods. Entity class may extend the entity as well as non-entity classes or vice-versa. The class must implement the serializable interface if an entity instance is passed by value.

Persistence Fields and Properties in Entity Classes: There are two ways to access the persistent state of an entity either by instance variables or by using the JavaBeans-style properties. The fields or the properties must follow the Java language types:

Java primitive types java.lang.String Other serialization types including: wrappers of java primitive types java.util.Date java.util.Calender java.math.BigDecimal java.math.BigInteger java.sql.Time java.sql.Date java.sql.TimeStamp User-defined serializable types char[] Character[] byte[] Byte[] Enumerated types Other entities and/or collection of entities Embedded classes

Entity uses the persistent fields while mapping annotations. Annotations are applied to the entity's instance variable. On the other hand entity uses the persistence properties while mapping annotations. Annotations are applied to the entity's getter methods for JavaBeans-style properties. We can not apply mapping annotations to both fields as well as properties simultaneously in a single entity.

Persistence Fields: Persistence accesses the entity class instance variables directly at runtime, if the entity class uses persistence fields. It is necessary to apply the object/relational mapping annotation on the instance variables. Persistent Properties: Entity must follow the method conventions of JavaBeans components while using the persistent properties. JavaBeans-style properties use getter and setter methods that are used after the entity class's instance variable names. There is a getter and a setter method for each persistence property. In case of a boolean property you may use isProperty instead of getProperty. Lets take an example to clarify this: Suppose an entity of type customer uses persistent property that has a private instance variable named firstName, the class defines two methods named getFirstName and setFirstName to retrieve and set the values of the instance variable. Use the following method signature for a single-valued persistent property.

Type getProperty() void setProperty(Type type)

Multi-valued (Collection-valued) persistent fields and properties must use the supported Java collection interfaces without worrying whether the entity uses the persistence fields or properties. The collection interfaces may be used at the following places:

java.util.Collection java.util.Set java.util.Map java.util.List

If the entity class uses persistent fields then the method signatures of the collection types must be one of these collection types. Suppose an entity of type customer includes a persistent property that uses a set of phone numbers then it should have the following methods: Set<PhoneNumber> getPhoneNumber() {} void setPhoneNumbers(Set<PhoneNumber>) {} The O-R mapping annotations must be applied to the getter methods. Note here that mapping annotations can not be applied to the fields or properties marked transient or annotated transient. Primary Keys in Entities:

Each entity contains a unique identity contained in the object. E.g. A customer entity has an identity that might be identified by the customer number. A primary key allows a client to be a particular entity instance. Every unique entity must be associated with a primary key. To prove its uniqueness every entity may have either a simple or a composite primary key.

To denote the primary key property or field Simple primary key use javax.persistence.Id annotations. Composite primary keys must be composed of either a single persistent property or field or a set of single persistent properties or fields. Composite primary keys uses javax.persistence.IdClass and javax.persistence.EmbededId. The primary key, or the fields of the composite primary key (like property or field) must follow one of the following Java language types.

Java primitive types Java primitive wrapper types java.lang.String java.util.Date (the temporal type should be DATE) java.sql.Date

Floating point types are not allowed to use in primary keys. Primary Key Classes: A primary class must follow the certain rules:

The class must have an access modifier as public. The class must include a public default constructor. Primary key must contain the properties of the type public or protected if property-based access is used. The class must be serialized. The class must implement the equals(Other other) and hashCode() methods. If the class has the mapping to multiple fields or properties of the entity class then the names and types of the primary key fields must match with those of the entity class.

The fields order_Id and itemId are combined together to make the primary key to uniquely identify thecomposite key. The code for managing composite key is shown as:

public final class ListItemKey implements Serializable{ public Interger order_Id; public int item_Id; public ListItemKey() {} public ListItemKey(Integer order_Id, int item_Id){ this.order_Id = order_Id; this.item_Id = item_Id; } public boolean equals(Object otherOb){ if(this == otherOb){ return true; } if(!otherOb instanceof ListItemKey){ return false; } ListItemKey other = (ListItemKey) otherOb; return ((order_Id==null?other.order_Id==null:order_Id.equals(other.order_Id)) &&(item_Id == other.item_Id)); } public int hashCode(){ return ((orderId==null?0:orderId.hashCode())^((int) itemId)); } public String toString() { return "" + orderId + "-" + itemId; } }
Multiplicity in Entity Relationships: There are four types of multiplicities defined for entity relationships like one-to-one, one-to-many, many-to-one, and many-to-many. One-to-one: When each entity instance is mapped to a single instance of another entity, then the mapping is known as one- to-one mapping. One-to-one relationships use the javax.persistence.OneToOne annotation on the corresponding persistent field or property.

For Example: A reference variable in java contains the address of a single object so that there exists only oneto-one mapping between the object of the reference variable. One-to-many: When an entity instance is related to many instances of other entities, then the relation is known as one-to-many. These types of relationships use the javax.persistence.OneToManyannotation on the corresponding field or property. For Example: A sales order may contain the order of multiple items so there is a one-to-many relationship between the sales order and the items. Many-to-many: When the multiple instances of an entity have the mapping to the multiple instances of the other entity then the mapping is said to many-to-many mapping. Many-to-many mapping relationships use the javax.persistence.ManyToMany annotation corresponding to the field or property. For Example: A college student have the admission in several courses while each course may have many students. Therefore there is many-to-many relationship between the students and the courses. Direction in Entity Relationships: A relationship can be either unidirectional or bi-directional. Unidirectional Relationship: A unidirectional relationship is a relationship in which only one of the two entities have the owing side. In unidirectional relationship only one entity can have the relationship property or field that may refer to the other. Example: In the example given above, the List_Item contains the relationship field that refers to the other entity named as Product, while the Product doesn't have any knowledge about the List_Item that refers to it. Bi-directional Relationships: A bi-directional relationship is the relationship in which both the entities have the owing side. In bi-directional relationship each entity in the relation have the relationship fields or property. Example: Suppose the Order in the above example have the knowledge about the List_Item instance it has and also suppose that the List_Item have the knowledge about what the Order it belongs to, then the relationship between them is said to be the bi-directional relation. Rules: There are some rules that each bi-directional relationship must follow:

You must use its owing side simply using the mappedBy element of the @OneToOne, @OneToMany, or @ManyToMany annotation of the inverse side of a bi-directional relationship.mappedBy element is used to designate the field or property in an entity.

In a one-to-one bi-directional relationship, owing side is the side that contains the corresponding foreign key. In a many-to-one bi-directional relationships the many side is always the owing side of the relationship and must not define the mappedBy element. In case of many-to-many bi-directional relationships either side may be the owing side.

Queries and Relationship Direction: Java Persistence query language navigates queries across relationships. The direction of the relationship can be determined by checking the navigation of a query from one entity to another. Example: In case of the unidirectional relationship, in the above example a query can navigate from List_Item to Product, but can not navigate from Product to List_Item. In case of the above Order and List_Item, a query can navigate in both the direction because both the entities have the bi-directional relationship. Cascade Deletes and Relationships: Entities having the relationships are dependent on other entities in the relationship. Lets take the above example to clarify this: While deleting the order, the list item is also deleted since it is the part of the order, this is known as cascade delete relationship. Use the element cascade=REMOVE element to delete the cascade relationships specified for @OneToOne and OneToMany relationship. Example: OneToMany(cascade=REMOVE, mappedBy="customer") public Set<Order>getOrders() { return order; } Entity Inheritance: Entities also supports the various features like inheritance, polymorphic queries, and polymorphic associations. Moreover they can also be the non-entity classes, while the non-entity classes can also extend the entity classes. These entity classes can be of the type either concrete or abstract. Abstract Entities: An abstract class can be defined as entity simply by declaring the class with the @Entity. The difference between the abstract and the concrete entities is that the concrete entities can be instantiated while the abstract entities can not. Concrete entities are queried same as the abstract entities. Suppose a query makes the target to an abstract entity then the query operates on all the concrete subclasses of the abstract entity.

@Entity public abstract class Student{ @Roll_no protected Integer StudentRoll_no; ............ } @Entity public class FullTimeStudent extends Student{ public Integer fee; ............ } @Entity public class PartTimeStudent extends Student{ protected Float classTime; }
Mapped Superclasses: We can inherit the entities from their superclasses containing the persistence state and the mapping information but are not entities. The super class does not need to decorate with the @Entity annotation, and does not map as an entity by the Java Persistence provider. These superclasses are used in most of the cases when the multiple entity classes have the common state and mapping information. Mapping superclasses are declared simply by specifying the class with thejavax.persistence.MappedSuperclass annotation.

@MappedSuperclass public class Student{ @Roll_no protected Integer

StudentRoll_no; ............ } @Entity public class FullTimeStudent extends Student{ protected Integer fee; .................. } @Entity public class PartTimeStudent extends Student{ protected Float classTime; ............. }
We can not query the mapped superclasses and can also neither be used in Query operations nor EntityManager. But use the entity subclasses of the mapped superclasses to perform the Query operations or EntityManager. Entity relationship can not target to the mapped superclasses. Mapped superclass can be either of concrete or abstract type and also don't have any corresponding table in the underlying database. Entities inherited from the mapped superclasses define the table-mapping. For instance the above code snippet contains the underlying table FULLTIMESTUDENT and PARTTIMESTUDENT but did not have any STUDENT table. Non-Entity Superclasses: As discussed above that the entities may have non-entity superclasses and these superclasses can either be abstract or concrete. The state of the non-empty superclasses and any state inherited from these superclasses are not persistent. Non-entity superclasses can be used either in Query operations or in EntityManager. While the non-entity superclasses ignore any mapping or relationship annotations.

Entity Inheritance Mapping Strategies: There is a way to configure the mapping between the underlying datastore and the inherited entities simply by decorating the parent class in the hierarchy with the javax.persistence.Inheritance annotation. Entities uses three types of mapping strategies to map the entity data to the underlying database.

A table for each concrete entity class. A single table for each class hierarchy. A "join" strategy for the specific fields or properties to a subclass are mapped to different tables rather than the fields that are common to the parent class.

You can configure the strategy simply by setting the "strategy" element of @Inheritance to one of the options defined in the javax.persistence.InheritanceType enumerated type: public enum InheritanceType{ SINGLE_TABLE, JOINED, TABLE_PER_CLASS }; InheritanceType.SINGLE_TABLE is the default strategy value and is used in such situations where @Inheritance annotation is not specified in the parent class of the hierarchy. Single Table per Class Hierarchy Strategy: This strategy corresponds to the default InheritanceType.SINGLE_TABLE, a single table in the database is mapped to all the classes in the hierarchy. This table includes a column containing a value to identify the subclass that belongs to the row represented by the instance. This column is known as discriminator column and can be specified by the javax.persistence.DiscriminatorColumn annotation at the root in the class hierarchy of the entity. The javax.persistence.DiscriminatorType enumerated type is used to set the type of the discriminator column in the database simply by setting the discriminatorTypeelement of @DiscriminatorColumn to one of the defined types. DiscriminatorTypeis defined as: public enum DiscriminatorType{ STRING, CHAR, INTEGER }; While @DiscriminatorColumn in not specified at the root of the entity hierarchy and the discriminator column is required then the persistence provider assumes the coulumn type as DiscriminatorTypeSTRING and column name as DTYPE by default.

A Java Persistence Example

Java Persistence API is the standard API used for the management of the persistent data and object/relational mapping. Java Persistence API is added in Java EE 5 platform. Persistence, deals with storing and retrieving of application data, can now be programmed with Java Persistence API starting from EJB 3.0. Every application server compatible with Java EE 5 supports the Java Persistent APIs.

Java Persistence API is a lightweight framework based on POJO for object-relational mapping. Java language metadata annotations and/or XML deployment descriptor is used for the mapping between Java objects and a relational database.

Entity:

An entity can be considered as a lightweight persistence domain object. An entity defines a table in a relational database and each instance of an entity corresponds to a row in that table. An entity refers to a logical collection of data that can be stored or retrieved as a whole. For example, in a banking application, Customer and BankAccount can be treated as entities. Customer name, customer address etc can be logically grouped together for representing a Customer entity. Similarly account number, total balance etc may be logically grouped under BankAccount entity.

Entity beans:

Entity beans are enterprises beans, which represent persistent data stored in a storage medium, such as relational database an entity bean persists across multiple session and can be accessed by multiple clients. An entity bean acts as an intermediary between a client and a database. For example, consider a bank entity bean that is used for accessing account details from a database. When a client wants to perform a transaction, the information regarding their specific account is loaded into an entity bean instance from the database. Operations are performed on the data present in the instance and updated in the bank?s database at regular intervals.

The EJB 3.0 entity beans are used to model and access relational database tables. It is a completely POJObased persistence framework with annotations that specify how the object should be stored in the database. The EJB 3.0 container does the mapping from the objects to relational database tables automatically and transparently. The Java developer no longer needs to worry about the details of the database

table schema, database connection management, and specific database access APIs.

Entity beans do not need to implement home interfaces and business interfaces. They are optional.

Mapping with EJB3/JPA Annotations: EJB3 entities are POJOs. Their mappings are defined through JDK 5.0 annotations (an XML descriptor syntax for overriding is defined in the EJB3 specification). Annotations can be split in two categories, the logical mapping annotations which allows programmer to describe the object model, the class associations, etc. and the physical mapping annotations which describes the physical schema, tables, columns, indexes, etc. The combination of annotations from both categories makes an entity-based application.

Primary Key Generation:

In EJB 3.0, a primary key is used with @Id annotation. Depending upon the application requirement, Id annotation can be used with different primary key generation strategies defined by GeneratorType enum. The GeneratorTypes are TABLE, SEQUENCE, IDENTITY, AUTO, and NONE. Declaring an entity bean: Every bound persistent POJO class is an entity bean and is declared using the @Entity annotation (at the class level):

@Entity public class Book implements Serializable { Long empid; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } }

@Entity declares the class as an entity bean (i.e. a persistent POJO class), which tells the EJB3 container that this class needs to be mapped to a relational database table. @Id declares the identifier property of this entity bean. @GeneratedValue annotation indicates that the server automatically generates the primary key

value.

The class Book is mapped to the Book table, using the column id as its primary key column.

Defining the table: @Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity bean mapping. If no @Table is defined the default values are used, that is the unqualified class name of the entity.

@Entity @Table(name="book") @SequenceGenerator(name = "book_sequence", sequenceName = "book_id_seq")public class Book implements Serializable {

The @Table defines the table name. Each instance of the entity bean represents a row of data in the table. Each column in the table corresponds to a data attribute in the entity bean. The@SequenceGenerator defines a sequence generator. A sequence is a database feature. It returns the next Integer or Long value each time it is called.

Managing Entities: The entity manager manages entities. The entity manager is represented byjavax.persistence.EntityManager instances. Each EntityManager instance is associated with a persistence context. A persistence context defines the scope under which particular entity instances are created, persisted, and removed. It is a set of managed entity instances that exist in a particular data store. The EntityManager interface defines the methods that are used to interact with the persistence context.

The EntityManager Interface: The EntityManager API creates and removes persistent entity instances, finds entities by the entity?s primary key, and allows queries to be run on entities. To obtain an EntityManager instance, inject the entity manager into the application component:

@PersistenceContext EntityManager em; Managing an Entity Instance's Life Cycle:

You manage entity instances by invoking operations on the entity by means of an EntityManager instance. Entity instances are in one of four states: new, managed, detached, or removed.

New entity instances have no persistent identity and are not yet associated with a persistence context. Managed entity instances have a persistent identity and are associated with a persistence context. Detached entity instances have a persistent identify and are not currently associated with a persistence context. Removed entity instances have a persistent identity, are associated with a persistent context, and are scheduled for removal from the data store. A Domain model of JPA represents the persistence objects or entities in the database.

There are following steps that you have to follow to develop a ?book? JEE application.
1. 2. 3. Create Remote business interface: BookCatalogInterface Implement the Annotated Session Bean: BookCatalogBean Create the Entity bean: BookBank

4. 5. 6.

Create the web client: WebClient Deploy book on the server. Run web client on the web browser.

I. The BookBank entity bean class: In the Book catalog example, we define a Book entity bean class. The bean has three properties (title, author and price) to model a Book product. The id property is used to uniquely identify the Book bean instance by the EJB3 container. The id value is automatically generated when the bean is saved to the database.

The code for the Book bean is given below.

package entity.library; import import import import import import import import javax.persistence.Entity; javax.persistence.GeneratedValue; javax.persistence.GenerationType; javax.persistence.Id; javax.persistence.Table; java.util.Collection; javax.persistence.*; java.io.Serializable;

@Entity @Table(name="bookbank") public class BookBank implements Serializable { long id; String title; String author; double price; //protected Collection <LineItems> lineitems; public BookBank() { super(); } public BookBank(String title, String author, double price) { super(); this.title = title; this.author = author; this.price = price; }

@Id @GeneratedValue(strategy=GenerationType.AUTO) // Getter and setter methods for the defined properties.. public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } }

The @Table annotation is used to specify the table name to be used by this Entity bean.

The @Id annotation is used to mark the id field as the primary key of the entity bean.

II. SQL Schema for the Book table mapped from the Book bean:

CREATE TABLE BOOKBANK ( ID int(11)

NOT NULL auto_increment, TITLE varchar(50) NOT NULL, AUTHOR varchar(50) NOT NULL, PRICE decimal(12,2) NOT NULL, PRIMARY KEY (ID) );
III. The Business Logic: Now, the next step is to develop the business logic of the application. The Book catalog application needs to be able to save a new Book object into the database and retrieve all existing Book objects from the database. We use EJB3 session bean POJOs to implement the business logic.

To implement a session bean, we first determine the interface it exposes. In the Book catalog application, this is a simple Java interface declaring all business methods.

package entity.library; import javax.ejb.Remote; import java.util.Collection; @Remote public interface BookCatalogInterface { public void addBook(String title, String author, double price); public Collection <BookBank> getAllBooks(); }

IV. Annotated Session Bean Implementation Class: The EJB3 container creates instances of the session bean based on the implementation classes. The application itself never creates session bean instances. It simply asks the container for an instance of the session bean to use, either through dependency injection or, for external components, through a JNDI lookup. The class is tagged with the @Statelessannotation, which tells the container that the bean object does not maintain any client state information between method

invocations. The caller component gets a fresh and random BookCatalogBeaninstance every time when it makes a bean method call.

In order to use the entity beans in the session bean, you need a special utility class called theEntityManager. The EntityManager acts as a generic DAO (Data Access Object) for all entity beans in the JAR. It translates operations on entity beans to SQL statements to the database. To obtain an EntityManager, the container creates one object and injects it into the session bean.

The addBook() and getAllBooks() methods in the BookCatalogBean class show the EntityManager in action. The EntityManager.persist() method takes a new entity bean POJO and writes it to the database.

The code for the BookCatalogBean is given below.

package entity.library; import java.util.Iterator; import java.util.Collection; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.io.Serializable; import javax.ejb.Remote; @Remote(BookCatalogInterface.class) @Stateless public class BookCatalogBean implements Serializable, BookCatalogInterface { @PersistenceContext(unitName="EntityBean") EntityManager em; protected BookBank book; protected Collection <BookBank> bookList; public void addBook(String title, String author, double price) { // Initialize the form if (book == null) book = new BookBank(title, author, price); em.persist(book); } public Collection <BookBank>getAllBooks() { bookList=em.createQuery("from BookBank b").getResultList(); return bookList; } }

The EntityManager API creates persistent entity instances and allows queries to be run on entities.

Context context = new InitialContext(); BookCatalogInterface bookcat = (BookCatalogInterface) context.lookup(BookCatalogBean.class.getName());


V. Web Client Code: Here is the full source code of the book client (WebClient.java):

<%@ page contentType="text/html; charset=UTF-8" %> <%@ page import="entity.library.*, javax.naming.*, java.util.*"%> <%! private BookCatalogInterface bci = null; String s1,s2,s3; Collection list; public void jspInit() { try { InitialContext ic = new InitialContext(); bci = ( BookCatalogInterface) ic.lookup("book/BookCatalogBean/remote"); System.out.println("Loaded Bank Bean"); } catch (Exception ex) { System.out.println("Error:"+ ex.getMessage()); } } public void jspDestroy() { bci = null; } %> <% try { s1 = request.getParameter("t1"); s2 = request.getParameter("aut"); s3 = request.getParameter("price");

if ( s1 != null && s2 != null && s3 != null) { Double price= new Double(s3); bci.addBook(s1, s2, price.doubleValue()); System.out.println("Record added:"); %> <p> <b>Record added</b> <p> <% } list=bci.getAllBooks(); for (Iterator iter = list.iterator(); iter.hasNext();){ BookBank element = (BookBank)iter.next(); %> <br> <p>Book ID: <b><%= element.getId() %></b></p> <p>Title: <b><%= element.getTitle() %></b></p> <p>Author: <b><%= element.getAuthor() %></b></p> <p>Price: <b><%= element.getPrice() %></b></p> <% } }// end of try catch (Exception e) { e.printStackTrace (); } %>

The source code for the "index.jsp' is given below that will actual call the client-design form.

<%@page language="java" %> <html> <head> <title>Ejb3 JPA Tutorial</title> </head>

<body bgcolor="#FFFFCC"> <p align="center"><font size="6" color="#800000"><b>Welcome to <br> Ejb3-Jboss 4.2.0 Tutorial</b></font> Click <a href="ejb3/form.jsp">Book

Catalog Example</a> to execute Library<br></p> </body> </html>

The source code for the index.jsp is given below that will call the web client.

<html> <head> <title>Library</title> </head> <body bgcolor="pink"> <h1>Library</h1> <hr> <form action="WebClient.jsp" method="POST"> <p>Enter the Title: <input type="text" name="t1" size="25"></p> <br> <p>Enter Author name: <input type="text" name="aut" size="25"></p> <br> <p>Enter Price: <input type="text" name="price" size="25"></p> <br> <p> <input type="submit" value="Submit"> <input type="reset"

value="Reset"></p> </form> </body> </html>

V. Deploy book application on the Application Server jboss-app.xml The jboss-app.xml file defines a class loader for this application. It makes it simpler for EJB 3.0 to find the default EntityManager.

<jboss-app> <loader-repository> book:archive=book.ear </loader-repository> </jboss-app>

Application.xml

<?xml version="1.0" encoding="UTF-8"?> <application xmlns="http://java.sun.com/xml/ns/javaee" mlns:xsi="http://www.w3.org/2001/XMLSchemainstance" version="5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_5.xsd">

<display-name>JPA Example</display-name> <module> <web> <web-uri>book.war</web-uri> <context-root>/book</context-root> </web> </module> <module> <ejb>book.jar</ejb> </module>

</application>

Put both files in the EntityBean\code\deploymentdescriptors\ear directory.

persistence.xml The persistence.xml file contains one or several persistence-unit element. Each persistence-unit defines the persistence context name, data source settings, and vendor specific properties. In this example, we are using the HSQL database that is default provided by the Jboss AS. The hibernate property ?create-drop? will automatically create & drop a table (according to the POJO class) each time when you deploy and run the application on server.

<persistence> <persistence-unit name="EntityBean"> <jta-data-source>java:/DefaultDS</jta-data-source> <properties> <property name="hibernate.hbm2ddl.auto" value="create-drop"/> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> </properties> </persistence-unit> </persistence>

Put this files in the EntityBean\code\deploymentdescriptors\jar directory. web.xml

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app > </web-app>

Start command prompt, and go to the EntityBean\code directory. Then type the command as: C:\ EntityBean\code>ant build.xml The Ant tool will deploy the book.ear file to the jboss-4.2.0.GA\server\default\deploy directory. VI. Running the book application Open the web browser and type the following URL to run the application: http://localhost:8080/book

Click at the given link as Book Catalog Example:

Enter the Title, Author and Price for the book to the textbox then clicks the Submit button to get the result.

EJB life cycle method

The various stages through which an enterprise bean go through its lifetime is known as the life cycle of EJB. Each type of enterprise bean has different life cycle. Here we are telling you about the lifecycle of message driven bean. This type of bean follow three steps: 1)setMessageDrivenContext:-This method is used to pass the context object to the instance.

2)ejbCreate:-This method is generated automatically whenever a new enterprise bean is created.

3)ejbRemove:-At this stage the bean instance is ready to move for the garbage collection. em.persist(newsEntity):-This method makes an entity instance that is managed and persistence. em.merge(newsEntity):-By using this method we can merge the state of the given entity into the current persistence context. em.remove(em.merge(newsEntity)):-This method is used for removing the entity instance. Here is the program denoting life cycle of message driven bean.

package ejb; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class NewsEntityFacade implements NewsEntityFacadeLocal { @PersistenceContext private EntityManager em; public void create(NewsEntity newsEntity) { em.persist(newsEntity); } public void edit(NewsEntity newsEntity) { em.merge(newsEntity); } public void remove(NewsEntity newsEntity) { em.remove(em.merge(newsEntity)); } }

S-ar putea să vă placă și