Showing posts with label EJB3. Show all posts
Showing posts with label EJB3. Show all posts

Difference b/w EJB2.1 and EJB3.0?

1.No need of Home Interface (EJBHome),but it is needed in EJB2.0

2.No more confusions to make an EJB remote or local,it's the client which would decide and cast to appropriate.

3.Just write SINGLE simple Java class and annotate it to be Stateless/Stateful/Entity/MessageDriven.Container

4.No Deployment Descriptors , MetaData Annotations are explored which is introduced in J2SE5.0

5.Forget all EJB life cycles.For example Entity bean life cycle in 3.0 is new,managed,detached,removed.

Ready to develop complex query,inner/outer join with EJB3.0.
. Click here to View more...

EJB 3 Using RAD7.5 and WebSphere

Introduction

This tutorial will show you how to use RAD7.5 beta to develop EJB3 applications.

Download and Install RAD 7.5 Beta

Download the code from the RAD7.5 Open Beta home page.

For more information and help, use the open beta forum.

Launch RAD7.5

From the Start menu, choose Programs->IBM Software Delivery Platform->IBM Rational Application Developer 7.5->IBM Rational Application Developer.

Enter a workspace folder name. Note: It is a good idea to use a short path name for the workspace to avoid Windows 255 character file name restriction.

Close the Welcome view.

Create an EJB Project

From the menubar, select File->New->Other.

Choose EJB->EJB Project. Click Next.

Enter these values:

Project name: TutorialEJB
EAR Project name: TutorialApp

Click Next.

Leave the Java Persistence facet unchecked for now. In this tutorial, we will develop session EJBs only.

Click Next.

By default, system will create a separate Java project to store remote interface and generated classes like stubs. These artifacts are required to compile and execute a client application. RAD refers to it as the client JAR project. In our case, system will create the TutorialEJBClient project.

Click Finish to create the EJB project and the enterprise application (EAR) project.

Create a EJB3 Session EJB

RAD7.5 lets you develop EJB 2.1 as well as EJB 3 compliant EJBs. The steps are quite different. Now, we will develop a EJB 3 compliant session EJB.

In EJB 3, a session bean does not need home interface. A remote interface is also optional but highly recommended. First, we will create the remote interface. The remote interface needs to be create in the client JAR project.

Right click the TutorialEJBClient project and select New->Interface.

Enter com.webage.ejbs as the package name. Enter HelloRemote as the interface name.

Click Finish.

In the interface file, enter the code shown in bold face.

@Remote
public interface HelloRemote {
public String sayHello(String name);
}

The @Remote annotation makes this otherwise basic interface a remote interface. Note, how you don't have to add special feature to the interface (for example, the method does not have to throw RemoteException).

Press Control+Shift+O to organize package names. This will import the javax.ejb.Remote interface name for the @Remote annotation.

Save and close the file.

Now, we will create the bean class in the EJB project.

Right click the TutorialEJB project and select New->Class.

Enter com.webage.ejbs as the package name and HelloBean as the class name.

Click Finish. System will open the class file.

First of all, we must designate the class as a stateless session EJB class using the @Stateless annotation.

RAD 7.5 supports code completion for annotations. Feel free to use it to add the @Stateless annotation at the class level.

@Stateless
public class HelloBean {

}

Now, we will make the class implement the remote interface. Add the code shown in bold face.

public class HelloBean implements HelloRemote {

Note: In EJB3, you can explicitly specify the name of the remote interface for an EJB using the @Remote annotation. This is necessary, only when an EJB supports both remote and local interface. Otherwise, as in our case here, system intelligently deduces that the EJB supports a remote interface and that it's name is HelloRemote.

Now, we will add the implementation of the sayHello() method.

Right click on the editor and select Source->Override/Implement Method.

System will automatically select the unimplemented methods (sayHello() in this case). Click OK.

Enter the code as shown in boldface below.

public String sayHello(String name) {
return "Hello " + name;
}

Now, press Control+Shift+O to organize imports.

Save the file. That's all there is to it.

Develop a Client

The Universal Test Client (UTC) of RAD can not be used to test a EJB3 EJB. We must code the client.

Now, we will develop a Servlet that will act as the client of the EJB. First, we will create a web project.

From the menu bar, select File->New->Other.

Select Web->Dynamic Web Project. Click Next.

Enter TutorialWeb as the project name. Make sure TutorialApp is selected as the application project.

Click Finish.

Click No.

Before we can create the client, we must add a dependency on the EJB client JAR project.

Right click the TutorialWeb project and select Properties.

Select the J2EE Module Dependencies property. Then, check TutorialEJBClient.jar.

Click OK.

What does that do? When the web project is exported as a WAR file, system automatically includes the TutorialEJBClient.jar file in the WEB-INF/lib folder of the WAR file. This allows the classes in the web module find the remote interfaces of the EJBs.

Now, we can create the Servlet. Right click the TutorialWeb project and select New->Servlet.

Enter com.webage.servlet as the package name. Enter TestServlet as the class name.

Click Finish.

In the Servlet class, add a EJB reference using the @EJB annotation as shown in boldface below.

 public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;

@EJB
HelloRemote hr;

Note a few items:

  1. The @EJB annotation is applied to a member variable that is either a local or remote interface of an EJB.
  2. In WebSphere, the default JNDI name of an EJB is set based on the remote or local interface name. As a result, here the @EJB annotation has enough information to deduce the JNDI name.
  3. The @EJB annotation works only in a Servlet or EJB bean class. You can't use it from a regular Java class, such as a JSF managed bean or Struts action. These classes must explictly do a JNDI lookup. In WebSphere, the JNDI name of an EJB is same as its remote interface name or ejblocal:LOCAL_INTERFACE_NAME.

Press Control+Shift+O to organize imports.

Now, implement the doGet() method as shown below.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

if (hr == null) {
out.println("

Could not locate EJB!

");
} else {
out.println("

" + hr.sayHello("Poppa John") + "

");
}
}

Save changes.

Now, we are ready to test the servlet.

Test

Start WebSphere Application Server v6.1.

After the server starts, deploy the TutorialApp application to the server. To do that, right click the server in the Servers view and select Add Remove Projects.

Wait for the publishing process to end.

Right click TestServlet.java in the Project Explorer view. Select Run As->Run on Server.

Click here to View more...

Inheritance Mapping in EJB3

Supported inheritance mapping strategies

The Teneo OR Mapper supports all three inheritance mapping of Hibernate (see chapter 9 of the Hibernate manual):

* SINGLE_TABLE: Table-per-class-hierarchy, in this scenario the classes of one class hierarchy are all mapped to one table.
* JOINED: Table-per-subclass, in this strategy each subclass will have its own table. To retrieve an object from the database the superclass and subclass tables are joined. This also applies to subclasses of subclasses.
* TABLE_PER_CLASS: table-per-class, each concrete class is stored in its own table. All properties (including inherited) are mapped to the table of the concrete class. Teneo uses the union-subclass concept of Hibernate to map table-per-class. The disadvantage is that generated id's are not supported. If you prefer the table-per-class implicit polymorphism approach of Hibernate then this can be (in a way) achieved by setting the mapped superclass annotation on the superclass. Note that with mapped superclass the superclass itself will not be persisted separately.

As a default SINGLE_TABLE inheritance mapping is used. There are two methods by which the inheritance mapping can be set.

1. Globally: pass the constant org.eclipse.emf.teneo.mapper.PersistenceMappingOptions.INHERITANCEMAPPING as a property when initializing a HbDataStore. This property can have two values: SINGLE_TABLE or JOINED.

2. By using an (EJB3) annotation for individual types: see below.

Hibernate has as main limitation that the two approaches above can not be mixed within one class hierarchy.

There is also another way of mapping inheritance structures: MappedSuperclass. In this method the superclass is not persisted by itself and does not have its own table. All the properties of the superclass are stored in the table(s) of the subclass(es). MappedSuperclass is set by an EJB3-like annotation. For more information see the EJB3 spec.
Specifying inheritance mapping per class hierarchy

There are cases where it is necessary to use different inheritance mapping techniques for different class hierarchy within one application or project. This can be achieved by adding specific EJB3-like annotations to the type definition (uml or XML Schema).

As an example see the following type definition of Address which sets the inheritance mapping strategy to JOINED (joined subclass) for Address and all its subtypes:



@Inheritance(strategy=JOINED)



The inheritance-mapping annotation can have one of the two following values: JOINED or SINGLE_TABLE.

The above annotation can also be added in UML. Please use the same values for the source and the key.

The inheritance annotation has changed, from the 0.3.* to the 0.7.0 release, to an EJB3-like format.
Multiple Inheritance Support

In EMF it is possible to define multiple inheritance structures. Although Hibernate itself does not support multiple inheritance Teneo does its best to map a multiple inheritance structure.
Choosing the real supertype

The following approach has been implemented in Teneo. During the mapping the first (non-MappedSuperclass, non-interface) supertype is considered to be the real parent (for Hibernate). If the type only has interface supertypes then the first one of these (which is not a mappedsuperclass) is chosen. The properties of the other super types are mapped together with the subclass. These other supertypes are treated as a MappedSuperclass (see the jpa/ejb3 spec). The other super types will have their own tables in the database but there will be no relations between the subclass table and its other superclass tables.

See as an example the figure below, the figure illustrates how a model is translated to a relational database schema using a joined-subclass inheritance mapping strategy. The SchoolBook inherits from both Book and Asset. This is translated into a relational model with SchoolBook refering to the chosen real supertype (Book) and also inheriting the value-efeature from Asset. This means that when the SchoolBook is read from the database then it will also implement the Asset interface/type and its value efeature is set correctly. On the other hand there is no relation to the Asset table (see limitation below).


Multiple Inheritance Example
Limitation

The main limitation is that references to supertypes do not (always) work correctly. Using the example above. According to the model and the generated code the AssetList can also contain SchoolBooks (as the type inherits from Asset). However, the database schema shows that a SchoolBook does not have a foreign key reference to the AssetList table. So when an AssetList with SchoolBooks is persisted the save action will fail.
The @Entity annotation, choosing a different supertype for relational mapping

As described above Teneo, as a default, chooses the first supertype as the one to use to generate the relational mapping. However there are cases (see here for example) that this is not desired and it is neither possible to change the supertype definition. In this situation you can use the @Entity annotation and its extends field. The extends field should be set to the entityname of the desired supertype. See the this annotations.xml as an example.
Other inheritance mappings: single-table, table-per-concrete-class, implicit polymorphism, any-reference

The example above uses a joined-subclass strategy. With single-table basically the same limitation applies. With table-per-concrete-class other limitations apply as described in the hibernate manual (chapter 9, section 9.2).

Implicit polymorphism should also work in case of multiple inheritance (querying for the Asset interface should return also SchoolBooks). This has however not been tested with Teneo.

The reference in the example can also be mapped using the hibernate any-reference. By using the any-mapping an AssetList with SchoolBooks can be persisted. However, the any-mapping has as main disadvantage that no referential integrity is enforced.
Click here to View more...

Life Cycles of Enterprise Beans


An enterprise bean goes through various stages during its lifetime, or life cycle. Each type of enterprise bean--session, entity, or message-driven--has a different life cycle.

The descriptions that follow refer to methods that are explained along with the code examples in the next two chapters. If you are new to enterprise beans, you should skip this section and try out the code examples first.

The Life Cycle of a Stateful Session Bean

Figure 3-3 illustrates the stages that a session bean passes through during its lifetime. The client initiates the life cycle by invoking the create method. The EJB container instantiates the bean and then invokes the setSessionContext and ejbCreate methods in the session bean. The bean is now ready to have its business methods invoked.

[Image]

Figure 3-3 Life Cycle of a Stateful Session Bean

While in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by moving it from memory to secondary storage. (Typically, the EJB container uses a least-recently-used algorithm to select a bean for passivation.) The EJB container invokes the bean's ejbPassivate method immediately before passivating it. If a client invokes a business method on the bean while it is in the passive stage, the EJB container activates the bean, moving it back to the ready stage, and then calls the bean's ejbActivate method.

At the end of the life cycle, the client invokes the remove method and the EJB container calls the bean's ejbRemove method. The bean's instance is ready for garbage collection.

Your code controls the invocation of only two life-cycle methods--the create and remove methods in the client. All other methods in Figure 3-3 are invoked by the EJB container. The ejbCreate method, for example, is inside the bean class, allowing you to perform certain operations right after the bean is instantiated. For instance, you may wish to connect to a database in the ejbCreate method. See Chapter 16 for more information.

The Life Cycle of a Stateless Session Bean

Because a stateless session bean is never passivated, its life cycle has just two stages: nonexistent and ready for the invocation of business methods. Figure 3-4 illustrates the stages of a stateless session bean.

[Image]

Figure 3-4 Life Cycle of a Stateless Session Bean

The Life Cycle of an Entity Bean

Figure 3-5 shows the stages that an entity bean passes through during its lifetime. After the EJB container creates the instance, it calls the setEntityContext method of the entity bean class. The setEntityContext method passes the entity context to the bean.

After instantiation, the entity bean moves to a pool of available instances. While in the pooled stage, the instance is not associated with any particular EJB object identity. All instances in the pool are identical. The EJB container assigns an identity to an instance when moving it to the ready stage.

There are two paths from the pooled stage to the ready stage. On the first path, the client invokes the create method, causing the EJB container to call the ejbCreate and ejbPostCreate methods. On the second path, the EJB container invokes the ejbActivate method. While in the ready stage, an entity bean's business methods may be invoked.

There are also two paths from the ready stage to the pooled stage. First, a client may invoke the remove method, which causes the EJB container to call the ejbRemove method. Second, the EJB container may invoke the ejbPassivate method.

[Image]

Figure 3-5 Life Cycle of an Entity Bean

At the end of the life cycle, the EJB container removes the instance from the pool and invokes the unsetEntityContext method.

In the pooled state, an instance is not associated with any particular EJB object identity. With bean-managed persistence, when the EJB container moves an instance from the pooled state to the ready state, it does not automatically set the primary key. Therefore, the ejbCreate and ejbActivate methods must assign a value to the primary key. If the primary key is incorrect, the ejbLoad and ejbStore methods cannot synchronize the instance variables with the database. In the section The SavingsAccountEJB Example, the ejbCreate method assigns the primary key from one of the input parameters. The ejbActivate method sets the primary key (id) as follows:

id = (String)context.getPrimaryKey();

In the pooled state, the values of the instance variables are not needed. You can make these instance variables eligible for garbage collection by setting them to null in the ejbPasssivate method.

The Life Cycle of a Message-Driven Bean

Figure 3-6 illustrates the stages in the life cycle of a message-driven bean.

The EJB container usually creates a pool of message-driven bean instances. For each instance, the EJB container instantiates the bean and performs these tasks:

  1. It calls the setMessageDrivenContext method to pass the context object to the instance.
  2. It calls the instance's ejbCreate method.

[Image]

Figure 3-6 Life Cycle of a Message-Driven Bean

Like a stateless session bean, a message-driven bean is never passivated, and it has only two states: nonexistent and ready to receive messages.

At the end of the life cycle, the container calls the ejbRemove method. The bean's instance is then ready for garbage collection.

Click here to View more...

General Tutorials, Java technologies

Java security in web applicationThis article gives an overview about different attack mechanisms against Java web applications and J2EE applications. It introduces available security concepts in Java like JAAS and Sandbox security. Furthermore, security related design patterns.
Date: 06-03-07
Log4j tutorial with Tomcat examplesThis tutorial explains how to set up log4j with email, files and stdout. It compares XML to properties configuration files, shows how to change LogLevels for a running application. Furthermore, we explain best practices on logging and exception handling.
Date: 06-03-07
Tips and tricks for eclipse and the plugin MyEclipseIn this Tutorial we present tips and trick for the development enviroment eclipse and the extension MyEclipse.
Date: 28-08-06
Java EncyclopaediaFirst pages of an encyclopaedia including javas common abbreviations and technolgies. We try to explain short and easily to understand the terms of the java world.
Date: 28-08-06
MyEclipse CSS editorThis paper describes the new and improved editors of MyEclipse for CSS files.
Date: 29-08-06
MyEclipse JavaScript editorThis paper describes the new and improved editors of MyEclipse for JavaScript and CSS files.
Date: 29-08-06

Struts, JSP and Servlets Tutorials

JavaServer Faces Tutorials

First Java Server Faces TutorialThis tutorial facilitates the first steps with the quite new framework JavaServer Faces (JSF). Step by step an example application (a library) will be created, which illustrate the different elements of the framework.
Date: 28-08-06
JavaServer Faces Navigation Tutorial (?)This tutorial explain the navigation handling in JSF and shows the usage with an small example application. We will show multiple and complex examples for navigation rules. For examples navigation outcomes depending on application logic, actions, static n
Date: 29-08-06
JavaServer Faces - Converter TutorialThis tutorial explains the usage of converters in JSF. It shows how you can use standard converters step by step using an example application.
Date: 29-08-06
JavaServer Faces - Validation & Error Handling (€)This tutorial explains the validation and the error handling in JSF and shows a step by step example application. The tutorials shows the standard validators but also the creation of custom validators.
Date: 12-01-08
JavaServer Faces - Developing custom converters (€)This tutorial explains how to develop your own converters. It shows the usage of own custom converter tags and overriding standard converter of basic types.
Date: 12-01-08
JavaServer Faces - Message ResourcesThis tutorial explains the internationalization of a web application using JSF message resource bundle.
Date: 12-01-08

Debugging, Testing and Tuning Tutorials

Debugging from JSP and Java ApplicationsThis tutorial gives you an overview of how to use the debugging feature of eclipse to debug your web or Java projects.
Date: 28-08-06
Eclipse Junit testing tutorialThis tutorial gives you an overview of the features of JUnit and shows a little example how you can write tests for your Java application using eclipse.
Date: 29-08-06
Junit Testing with Struts (StrutsTestCases extension)This tutorial gives you an overview about the StrutsTestCases extension of JUnit and example how you can use it to test your Struts application.
Date: 29-08-06
Junit Testing Enterprise Java Beans (EJB) (?)This tutorial will demonstrate how to use Junit to unit test Enterprise JavaBeans.
Date: 29-08-06


Database Development, EJB and Hibernate Tutorials


Jboss Tutorials

Jboss as windows serviceInstallation of Jboss as windows service on windows 2000 and windows XP
Date: 28-08-06
Click here to View more...

EJB 3 and JPA Project Setup

Skeleton Project Setup


  1. Download this file: JpaAndEjb3.7z
  2. Download this file: Ejb3AndJpaPrefs.epf
  3. Use 7-zip to expand this file somewhere (for this example we'll use C:/workspaces)
  4. Start Eclipse
  5. Select the directory where you extracted this file and add to it JpaAndEjb3 (C:/workspaces/JpaAndEjb3)
  6. Pull down the File menu and select Import
  7. Under the General tab, select Prefererences and click Next
  8. Click Browse* and select the file you downloaded in the second step
  9. Click Finish
  10. Pull down the File menu and select Import
  11. Under the General tab, select Existing Projects into Workspace
  12. Click on Browse and go to the workspace directory and click OK (C:/workspaces/JpaAndEjb3 - note you should just be able to click Browse and then OK)
  13. Select all of the listed projects and click Finish**
Click here to View more...