Showing posts with label MyEclipse. Show all posts
Showing posts with label MyEclipse. Show all posts

JPA Tutorial



Table of Contents

  1. Introduction
  2. Suggested Audience
  3. System Requirements
  4. Getting Started
  5. Reverse Engineering
  6. Writing an Application
  7. Conclusion
  8. FAQ
  9. Resources
  10. Feedback

1. Introduction

Welcome to the MyEclipse JPA tutorial. In this tutorial we are going to take a look at some of the new JPA-based features in the MyEclipse 5.5 release and beyond. The project developed in this tutorial is available in ZIP format in our Resources section below.

JPA is the new Hibernate-like persistence specification that has become part of the Java EE 5 spec itself. JPA uses Java 5 annotations to control how plain Java classes (POJOs) get mapped to database tables. The MyEclipse tooling for JPA offers powerful generation and automation in the form of mapping existing DB tables directly to generated POJOs that are ready to be used against that database. MyEclipse also offers additional features for JPA in the Java source editor with reference to the annotations used to annotate the entities. MyEclipse will provide validation and autocomplete against the DB resources that the POJOs are referencing. For more general overview of JPA features offered in MyEclipse see the MyEclipse JPA Overview document.

2. Suggested Audience

This tutorial is intended for developers who are somewhat familiar with MyEclipse or Eclipse so you recognize navigation within the IDE, and understand some of the more common views like the debugger. It is also encouraged that the reader understand the basic idea of how JPA and entity mapping works along with annotations.

To learn more information about the topics presented in this tutorial please have a look at the links in our Resources section. To get a better feel for MyEclipse and learning more about it, please check out our product Documentation for more material.

3. System Requirements

This tutorial was created with MyEclipse 6.0. If you are using another version of MyEclipse, most of these screens and instructions should still be very similar.

If you are using a newer version of MyEclipse and notice portions of this tutorial looking different than the screens you are seeing, please let us know and we will make sure to resolve any inconsistencies.

4. Getting Started

Getting started with JPA in MyEclipse starts with two things:

  1. Having a project with JPA Capabilities added to it
  2. Using the DB Explorer to select table(s) to reverse-engineer using JPA

In MyEclipse you can add JPA Capabilities to many different kinds of projects. The most common are adding those capabilities to a Java Projects or Web Projects. In this tutorial we are going to use a simple Java Project to see how JPA works.

Setting up Your Project

First create your new project:

Now that your project is created, the next step is to create a DB Connection that we wish to use with this project. We cannot add JPA Capabilities until we have setup that connection because selecting the connection we wish to associate this project with is part of the JPA Capabilities wizard.

Setting up DB Connection

One of the new features since MyEclipse 5.5 is that it ships a preconfigured DB Connection pointed at an embedded install of the Apache Derby DBMS. Developers can immediately use this connection without needing to setup their own DBMS or connection.

To set up a DB connection first switch to the Database Explorer Perspective:

... and select the MyEclipse Derby connection, and click Open Connection before you start using it. This will automatically start the embedded MyEclipse Derby server and you'll have an instant access to all the tables in the database:

When you first connect to the Derby DB, MyEclipse ships a few sample schemas namely CLASSICCARS and MYBLOG :

The table we are going to work with is the PRODUCTLINE table. It contains a lot of sample data that you can view by right-clicking on the table and going to Edit Data:

Adding JPA Capabilities

Now that our DB Connection is setup and project is ready we need to add JPA Capabilities to our project in order to enable it to use tables and information from this DB Connection.

First, switch back to the MyEclipse Perspective, then right-click on the project and go down to the MyEclipse sub menu. From there, select Add JPA Capabilities...:

All the defaults on the first page of the JPA wizard are fine:

On the second page of the wizard we need to specify a name for our persistence unit. Any friendly name will work, we suggest using some variation of the project name for ease. Then we must specify the DB Connection and DB Schema to relate this project to. When you are done, click Finish:

Now our project has fully configured JPA Capabilities added to it, which include JPA configuration information, DB Connection information and all necessary JDBC and JPA libraries added to the project's build path. If this project were a Web Project, all the build-path additions would be prepared for deployment when the project was deployed to an app server and ran.

One last step is to create a new Java Package to reverse-engineer our entities into:

Then create a new package to place the classes in:

5. Reverse Engineering

Now that our project is setup, we are ready to reverse-engineer our PRODUCTLINE table into the project and start using the entities that are generated.

Right click on the JPA enabled project and select MyEclipse>Generate Entities from the context menu, as shown in the figure below:

In the reverse-engineering dialog that comes up, select the tables that you would want to reverse-engineer and hit Next. As an example we'll add the PRODUCTLINE table from the available tables list.

In the dialog that comes up next, you will want to fill out the following fields:

  • Java source folder: The folder in your project where the files will be generated
  • Java package: The package, that we created above, to place the generated classes
  • Entity Bean: Tell MyEclipse to generate plain Java classes that are correctly annotated to be used as JPA entities
    • Create abstract class: If you wish to customize the generated classes without fear of overwriting your changes each time, MyEclipse can generate base abstract classes as well as concrete subclasses that you can customize and use. Each time you reverse-engineer, MyEclipse will only overwrite the abstract base class, maintaining your changes in the concrete subclass.
    • Update persistence.xml: Similar to Hibernate, you can list all the JPA entities you will be using in the JPA configuration file.
  • Java Data Access Objects: Tell MyEclipse to generate DAO utility classes for you that allow you to save/find/update/delete the entities from the database right away. This code wraps the JPA entity manager and makes using the entities and the DB very easy.
    • Generate Precise findBy Methods: Tells MyEclipse to generate findByXXX methods where XXX pertains to each property on the entities that are reversed. This allows easy access to entities from the DB using any property as a means of finding them.

When we are done filling out the dialog, we can hit finish to reverse-engineer the table:

After reverse-engineering is done, we can go to the Persistence Perspective to use some of the persistence and datasource tools to analyze data in our DB and project. For the purpose of this tutorial we are going to flip back to the MyEclipse Perspective and take a look at the resources that MyEclipse generated for us:

Looking at them one at a time, we have:

  • Productline: This class is the JPA Entity (POJO) that represents the DB table PRODUCTLINE. This POJO has all the fields of the PRODUCTLINE table and represents one row in that DB.
  • ProductlineDAO: This class wraps the EntityManagerHelper to give us easy-to-use methods specifically for adding/finding/updating and deleting Productlines from the DB.
  • EntityManagerHelper: When using straight JPA, developers need to make use of the EntityManager class. This generated helper class tries to make using the EntityManager a much easier process by providing static methods to access the manager as well as the most common operations readily available to call.

6. Writing an Application

Now that MyEclipse has generate all this code for us, we can quickly focus on writing our "Business Logic", or more specifically, "the code that actually does stuff". In this tutorial we are going to keep things simple and write a single Java class, with a main method that inserts a Productline into the database, retrieves it, updates it and then deletes it. From this code you should be able to quickly see how easy it becomes actually using the JPA entities in your own applications without needing to write JDBC code or any other persistence code.

First, let's create our new Java class:

When the new class dialog pops up, be sure to give the class a name and tell the wizard to generate a main method:

After our new class and main method are generated, we need to write code that will successfully manipulate instances of Productline.

NOTE: The following code looks long and complex, but that's only because we are trying to show 4 different examples in one block of code. If you look at each operation (save, load, update, delete) none of them consist of more than a few lines of code.

That code is going to look like the following:

/* 1. Create a reference to our ID */
String productLineID = "Men's Shoes";

/* 2. Create a new Productline instance */
Productline newProductline = new Productline(
productLineID,
"Shoes for men.",
"Men's Shoes", null);

/* 3. Create a DAO instance to use */
ProductlineDAO dao = new ProductlineDAO();

/* 4. Store our new product line in the DB */
EntityManagerHelper.beginTransaction();
dao.save(newProductline);
EntityManagerHelper.commit();

/* 5. Now retrieve the new product line, using the ID we created */
Productline loadedProductline = dao.findById(productLineID);

/* 6. Print out the product line information */
System.out.println("*NEW* Product Line [productLine="
+ loadedProductline.getProductline() + ", textDescription="
+ loadedProductline.getTextdescription() + ", image="
+ loadedProductline.getImage() + "]");

/*
* 7. Now let's change same value on the product line, and save the
* change
*/

loadedProductline.setTextdescription("Product line for men's shoes.");

EntityManagerHelper.beginTransaction();
dao.save(loadedProductline);
EntityManagerHelper.commit();

/*
* 8. Now let's load the product line from the DB again, and make sure
* it text description changed
*/

Productline secondLoadedProductline = dao.findById(productLineID);

System.out.println("*REVISED* Product Line ["
+ "productLine=" + secondLoadedProductline.getProductline()
+ ", textDescription=" + secondLoadedProductline.getTextdescription()
+ ", image=" + secondLoadedProductline.getImage() + "]");

/* 9. Now let's delete the product line from the DB */
EntityManagerHelper.beginTransaction();
dao.delete(secondLoadedProductline);
EntityManagerHelper.commit();

/*
* 10. To confirm the deletion, try and load it again and make sure it
* fails
*/

Productline deletedProductline = dao.findById(productLineID);

/*
* We use a simple inlined IF clause to test for null and print
* SUCCESSFUL/FAILED
*/

System.out.println("Productline deletion: "
+ (deletedProductline == null ? "SUCCESSFUL" : "FAILED"));

Main class that uses JPA

NOTE: The code above in green are the markers for the beginning and the end of each transaction. It is a good idea to wrap segments of code that change the database with transactions, so if the operation fails (e.g. DB crashes) then all the changes that tried to occur in the transaction are rolled back to their original values instead of only half of the work getting done.

The code above may look daunting, but that's only because it's doing a lot of simple things back-to-back. If, for example, you were only interested in storing a new item in the database, you'd just have the code from Steps 1-3 in your program, which amounts (minus comments) to 3 lines of code. Not too shabby. Let's break each numbered section down now and look at what this code does:

  1. The PRODUCTLINE table uses the name of the product line as the primary key. To make this tutorial easier to follow, we simply define our product line name in a String and reuse it throughout the code (to create and store the product line, then to retrieve it twice). You could just as easily retyped "Men's Shoes" multiple times, but we thought this made the tutorial easier to follow.
  2. Here we are creating the new instance of the Productline POJO that was generated by MyEclipse and will be inserted into the DB. For the purpose of this tutorial the values are not important, so we just used some example info in there.
  3. Here we create an instance of the DAO to use. We need the DAO to do the actual DB access. This was generated by MyEclipse as well.
  4. Here we tell the DAO to actually store our new Productline in the DB. Because we are going to write something to the DB, we wrap our save call here in a transaction.
  5. In order to make sure that our Productline was stored correctly, using the ID we defined in Step #1 we ask the DAO to get our Productline and we assign the result to a brand new object, just to make absolutely sure that what is loaded, is from the DB. (We could have assigned the value back to newProductline, but for the purpose of the tutorial we wanted to be very obvious where objects are coming from and that the loaded instance hadn't existed before in our code accidentally).
  6. Here we print out the values from the loaded entity to make sure it's what we just stored in the DB.
  7. Here we change a value on the POJO we just loaded, to show how updating records work. And then we commit that change back to the DB using our DAO. Again this operation is wrapped in a transaction to make sure that our change to the DB is made safely.
  8. Just like in Step #5, here we are reloading the record from the DB, using it's ID we defined in Step #1 to make sure the update operation worked. We then print out the POJO values to make sure the new description did get saved to the DB.
  9. Here we are showing how deleting a record from the DB works. And again, because this requires a change to the DB, we wrap this code in a transaction as well.
  10. Similar to our Step #8 and Step #5, to prove that the delete worked, we try and load the entity from the DB using the ID we gave it. This operation should fail because we already erased the Productline. After we get the result from the DAO, we print out a statement with an embedded IF clause to make sure the result was null.

The output from running this looks like this:

The red text are default log messages from the generated DAO and EntityHelper classes in MyEclipse. The black text are the System.out.println text that we put in our code to track the progress through our code. As you can see the first print out from Step #6 and the updated print out from Step #8 all worked as expected. Also our deletion was successful as well since there was no Productline returned from our query after we erased it.

7. Conclusion

We have reached the end of our MyEclipse JPA tutorial. In this tutorial we tried to show not only the strengths of JPA as a persistence technology, but also of how much code MyEclipse will generate for you, allowing you to start coding your application immediately.

If you have any suggestions for us to help make it more informative, please let us know.

Below we would like to provide you with some more information pertaining to the topic covered in this tutorial. We offer the FAQ section for quick references to common questions and the Resources section with links to other helpful resources online that you may want to become familiar. We realize we can't cover every question you may have in one tutorial, but between this tutorial contents and our additional learning resources we hope you are far on your way to feeling comfortable with the technology.

8. Resources

In this section we want to provide you with additional links to resources that supplement the topics covered in this tutorial. While this is not an exhaustive list, we do make an effort to point to the more popular links that should provide you with diverse, high-quality information.



Common Reference

Misc Reference


Click here to View more...

Hibernate Introduction Tutorial



Table of Contents

  1. Introduction
  2. Suggested Audience
  3. System Requirements
  4. Introduction to Hibernate
  5. Getting Started
  6. Reverse Engineering
  7. Writing and Running Hibernate Code
  8. Conclusion
  9. FAQ
  10. Resources
  11. Feedback

1. Introduction

Welcome to the MyEclipse Introduction to Hibernate tutorial. In this tutorial we are going to cover some of the basic features of using the Hibernate framework, such as OR-mapping from within MyEclipse.

At it's core, Hibernate is an OR-mapping technology that is used to map database structures to Java objects at runtime. Using a persistence framework like Hibernate allows developers to focus on writing business logic instead of writing an accurate and performant persistence layer (which includes, DAOs, SQL queries, JDBC code, connection management, etc.).

However, to begin using Hibernate, you normally must generate the proper persistence mappings for Hibernate to manage, set up the database connection information and code the DAOs that read or write your mapped entities. Fortunately, MyEclipse developers don't need to do any of that because MyEclipse will generate all of this code for you. And that bit of code automation frees you up for the most important task of all: writing your application logic.

2. Suggested Audience

This tutorial is intended for developers who are somewhat familiar with either MyEclipse or Eclipse so you are expected to recognize navigation within the IDE and understand some of the more common concepts like "Views". Additionally, developers should be familiar with persistence in Java (JDBC, EJB, iBatis, JPA, etc.) to be able to understand the role Hibernate plays more quickly. While this tutorial will also introduce some of the basics of Hibernate, it is not intended to replace the detailed Hibernate Reference Guide found on the Hibernate site and in the Resources section below. There is a lot of functionality in Hibernate that allows it to scale to support enterprise-class applications, and those details can be learned from reading through the reference or a good Hibernate book.

If either MyEclipse or Hibernate makes you feel uncomfortable, this introductory tutorial should provide you with the basics of both. If you wish to learn more about either MyEclipse or Hibernate please have a look at either our product Documentation for more material or our Resources section respectively.

3. System Requirements

This tutorial was created with MyEclipse 5.1 and the bundled Hibernate 3.1 libraries. If you are using a another version of MyEclipse or Hibernate, most of these screens and instructions should still be very similar.

If you are using a newer version of MyEclipse and notice portions of this tutorial looking different than the screens you are seeing, please let us know and we will make sure to resolve any inconsistencies.

4. Introduction to Hibernate

In the early years of Java database and web programming, developers accessed their databases using the different classes provided by the java.sql package; you may even remember doing this yourself. Such usage consisted basically of getting a Driver from the DriverManager, creating a Connection, using the Connection, handling exceptions properly, closing the connection and so on. A common problem at this stage was forgetting to clean up database connections and getting connection exceptions in your applications after they had been running for a while.

A few years later "connection pools" became a big topic since they allowed the developer to stop worrying about creating and managing (cleaning up) DB connections and instead focusing on their SQL and ResultSet parsing code. Suddenly, we had mostly solved the problem of connection exceptions to the database in long-running applications. However, it was still common to see hundreds of lines of boiler-plate code used to populate queries with values and parse the ResultSets returned from SQL queries.

A few more years went by and someone had an idea to automatically map ResultSet results directly to Java objects, which mostly solved the problem of all the redundant boiler-plate parsing code. At that point in time Java database development had taken a several big steps forward and was getting much simpler. Then Hibernate came into the picture.

With Hibernate came the idea that not only would it continuing doing all these automated things for you, but it would also manage the state of your objects in memory and it would worry about when and how object values would be "read from" or "written to" the database. Now all the sudden developers were dealing completely with objects (or mapped objects) and letting Hibernate handle everything else. Developers were no longer writing JDBC and SQL code at all. Instead they were using code that automatically did all that work for them.

At the time Hibernate came on the scene, the other persistence technology out there was EJB 2.x. Hibernate's timing, ease of use and power all contributed to one of the fastest uptakes of a technology that the Java space that had been seen in quite awhile.

In this tutorial we are going to take a look at how using MyEclipse with Hibernate can make your life even easier than using Hibernate alone. In fact, MyEclipse removes the need to write any of the Hibernate mappings or configuration files by completely generating the persistence side of your Java application in just a few seconds.

We will start off with a simple database that we will reverse-engineer into a Hibernate-enabled project. Then, we will write some simple Java code to utilize the Hibernate code that MyEclipse generated automatically in order to store, retrieve and update information in our database.

5. Getting Started

The project we create during this tutorial, as well as the create-table SQL script for the database table we used, can be found in our Resources section below for those of you that want to peak ahead. For the rest, we would highly encourage you to follow along with the tutorial, creating the project as we go.

To get started with Hibernate in MyEclipse the first thing we need is a connection to the database that we want to build our application to use. In this particular case, it is an instance of MySQL 5 with a sample user table we've already created. We are also using the MySQL Connector/J JDBC driver to connect to our install of MySQL. So let's get started by creating a new connection, in MyEclipse, to our database:


Figure 1. Creating a connection to our database

Now that we have a working connection to our database, the second thing we need before we get started is a Hibernate-enabled project (Java, Web, Web Service, etc). We can create such a project by creating any of the supported types of base projects, like a Java or Web project, then adding Hibernate capabilities to that project from the MyEclipse menu, like so:


Figure 2. Creating a Hibernate-enabled project

6. Reverse Engineering

Now that we have a database connection and a project properly configured, the next thing for us to do is tell MyEclipse to reverse-engineer our database table into Hibernate (Java) objects and put them into our project.

In the example below we use the simplest form of reverse-engineering, letting the wizard take all the default values. However, for maximum control you could optionally use the Next button and step through the wizard to select details like primary key generation strategy, object names, types and more. Let's reverse-engineer our table now:


Figure 3. Reverse-engineering our user table into Hibernate (Java) objects

Now that our table has been reverse-engineered into our project, there are all sorts of Hibernate tools we can use in MyEclipse to work with those objects (even without writing code!). The first tool we will look at is the HQL Editor.

The HQL Editor, and other HQL views in the Hibernate perspective, assist in the development, evaluation or testing of HQL queries. HQL is a SQL-like language called "Hibernate Query Language". It can sometimes look like simplified SQL and uses object names and references instead of table and column names. A great place to learn about HQL is the Hibernate Reference Document in our Resources section.

With the HQL Editor you can actually write HQL on the fly into the editor, then run it. The editor, utilizing the objects that MyEclipse has reverse-engineered from the database, will actually translate the query to SQL (shown in the bottom right) and then run it. The result is returned in Java objects and is shown in the bottom left corner. Let's have a look at how this works now:


Figure 4. Using the HQL Editor and HQL Views

7. Writing and Running Hibernate Code

It is important to be familiar with the tools that MyEclipse provides, but since we've just taken a look at some of the nicer tools included, it's time to start writing our own code!

As mentioned before, one of the nicest parts of using MyEclipse to work with Hibernate is the fact that it generates all the boiler-plate Hibernate mapping and even DAO code for you. This means that after you are done reverse-engineering a database you are ready to start writing your application to read, write and update objects in your database.

In this tutorial we will write a series of simple methods that do 3 things in the following order:

  1. Create a new User and add him to the database
  2. Load a User from the database, using his primary key, and print out its information
  3. Change the User's values, update that record in the database and print the changed values to verify

The three methods ( addUser, listUser, changeUser) are all called from the main method in our new class. To better understand how this Hibernate code is written, let's create that class, put those methods in the class (using copy & paste) and then review them line-by-line:


Figure 5. Creating a new class that uses our generated Hibernate code

After looking at that code we can see how straight forward everything is. We use the DAO classes that MyEclipse generated for us to get, update and save our objects to the database and MyEclipse/Hibernate take care of all the other details for us. It couldn't get much easier than this.

Now to the fun part, let's run the code and see if it actually does the right thing:


Figure 6. Running our example Hibernate code

Very nice, it worked correctly just as we had hoped! We used the HQL Editor to query our database and make sure that our user was saved to it. Additionally, we could have just as easily switched to the Database Perspective and queried the database from there to see that the user record was in the table.

8. Conclusion

While the application in this tutorial may seem simple, the techniques and information provided is critical to understanding both Hibernate and MyEclipse. The fundamentals presented in this tutorial apply to pretty much any Hibernate-enabled application you would want to develop: the core idea of object mapping to the database. After getting these basics working, you are free to enhance, extend or change your application in any way you need to and be assured that MyEclipse will continue to help you develop and extend it.

We hope you have found this tutorial helpful. If you had comments about this tutorial or suggestions/questions for us, please let us know. We always value our user's feedback especially on educational materials such as these.

9. FAQ

  1. How does Hibernate compare to EJB 3 / JPA?
    • Hibernate 3.2 is actually JPA-compatible, implementing all the new annotations that make JPA so automatic and painless to use. So instead of using a commercial implementation of JPA, you can use Hibernate and still keep all the standard JPA annotations in your classes without any changes.
  2. Can Hibernate scale to very large applications?
    • Yes. Actually the roots of Hibernate come from the two founders own experiences working as consultants on large enterprise applications. Hibernate is their vision of how persistence should function in an application. Also a few years ago, Gavin King, put out a challenge to the community to find hand-tweaked JDBC SQL that executed a magnitude faster than the generated SQL from Hibernate to make a point that the framework is very focused on being functional, flexible and performant.
  3. Do I need all the Hibernate libraries in my application? There are a lot of them!
    • Not necessarily. Hibernate is a very complex framework and makes use of a lot of other 3rd party frameworks. Depending on what you are doing with Hibernate it's possible that you don't need a lot of the JARs that are in your build path. There is a README that ships with Hibernate in the /lib directory explaining which each library does if you really want to trim back your deployment footprint.
  4. What is the "Session" in Hibernate? Why do I need to bother with it?
    • Hibernate does a lot of "magic" under the covers. Part of that magic is to monitor mapped object's state and see if they have changed (e.g. a setter has been called) an then persist the changed values to the database in a timely fashion. In a small system you could imagine Hibernate managing all the objects at a time, but in bigger enterprise systems where there may be millions of mapped objects loaded at a time, a computer simply wouldn't have enough memory or CPU cycles to process so many entities. This is where the "session" comes into play. A Hibernate session represents a container of all the objects processed since that session has been opened. Most folks find that making a session the length of a transaction works for them, although for performance-critical applications that might be too short of a span of time for the session to exist when weighed against the cost of creating one. Another Hibernate session design is to use a ServletFilter to open a Hibernate session when a new HTTP session is created and then close the Hibernate session when the HTTP session is destroyed. For most small to mid-sized web applications running on a server with a decent sized heap this is a great balance between performance and memory requirements. Although you should always be aware of what objects you are loading and saving to a database, because if the session is left open, it's possible those objects could be hanging around in memory.
  5. MyEclipse FAQ
    • Support Forum FAQ

10. Resources

Below are links to resources that we hope will help answer most of the questions you could have while working your way through this tutorial pertaining to Hibernate:

Files

Reference

Basics


Click here to View more...

MyEclipse EJB 3.x Tutorial


Table of Contents

  1. Introduction
  2. Suggested Audience
  3. System Requirements
  4. Getting Started
  5. Creating a Stateless Session Bean
  6. Testing the Bean
  7. Conclusion
  8. Resources

1. Introduction

Welcome to the MyEclipse EJB 3 Tutorial. In this tutorial we are going to cover the development of an EJB 3 Stateless Session bean. It is important to note that because JPA Entities and EJB 3 Entities are so similar, developing an EJB 3 Entity Bean will not be covered in this tutorial and we would encourage you to read through the MyEclipse JPA Tutorial to see how that process works.

It is also important to be aware of this tutorial's scope, because during the creation of an EJB Project, you are asked to specify datasource information in case you decide to generate EJB3 Entities. We skip that portion in this tutorial because we are simply developing a Stateless Session Bean.

The project created in this tutorial is available in the Resources section for folks that would like to jump ahead.

2. Suggested Audience

This tutorial is intended for developers who are somewhat familiar with MyEclipse or Eclipse so you recognize navigation within the IDE, and understand some of the more common views like the debugger. Familiarity with EJBs in general and EJB3 are helpful, but not necessary. The concepts covered are fairly straight forward to Java developers.

To learn more information about the topics presented in this tutorial please have a look at the links in our Resources section. To get a better feel for MyEclipse and learning more about it, please check out our product Documentation for more material.

3. System Requirements

This tutorial was created with MyEclipse 5.5. If you are using a another version of MyEclipse, most of these screens and instructions should still be very similar.

If you are using a newer version of MyEclipse and notice portions of this tutorial looking different than the screens you are seeing, please let us know and we will make sure to resolve any inconsistencies.

4. Getting Started

The first thing we need to do is create a new EJB Project so we can create our EJB in it. First click on File > New > Project:

Then select the EJB Project and hit Next:

On this screen be sure to fill out the project's name and select the Java EE 5.0 specification level (which includes the EJB 3.0 spec):

On this next screen we can optionally configure any datasource we plan on using for this project to generate EJB3 Entity Beans, but as mentioned above, we are not going to show that in this tutorial (Hint: Please read the MyEclipse JPA Tutorial to get an idea of how working with entities is done). So we disable both these sections and Finish creating the project:

Our new project will look very simple, like this:


5. Creating a Stateless Session Bean

Now that our project is ready we should create a package to put our bean in:

And after the package is created, you will have a source folder that looks like the following:

Now, before we create our Session Bean, let's discuss how we can define our bean's functionality.

When the Session Bean is generated, it will implement two interfaces, 1 for Local calls (in the same VM) and 1 for Remote calls (Outside VM, over network, etc.). It is possible to have different functionality exposed based on the caller (e.g. don't expose methods to Remote invocation that return huge data sets). But for this tutorial, and in some cases, you will expose exactly the same information to your Local and Remote callers of your bean. Because of this assumption, we can keep our code easy to follow by implementing a base interface with all our methods defined in it, that both our Local and Remote versions of the bean extend and our Session Bean implements. The result ends up looking like this:

So let's create that base interface now:

When we create the new interface, we want it to extends Serializable so the application server can better handle the Session Bean if it need to:

And when the interface is created, we add a single method signature to it:

Now that our interface is ready, let's create our new EJB3 Session Bean:

On this next screen we want to name our bean, but also want to be sure to tell MyEclipse to generate Local and Remote interfaces for it:

Now that our bean is generated with the Local and Remote interfaces as well, we end up with this:

We want to modify the MyBeanLocal and MyBeanRemote interfaces to extend IMyBean as well as add the implementation for doSomething() to MyBean. If we hadn't defined IMyBean, we would have to copy-paste the method definitions from it to both MyBeanLocal and MyBeanRemote anyway to expose those methods. Defining the methods in a single interface makes things a bit easier. As a reminder, we now have this structure:


The one last thing for us to do is add a simple implementation for the doSomething() method. For the purpose of this tutorial, a typical "Hello World" will suffice:

public void doSomething() {
System.out.println("Hello World!");
}

Simple Hello World implementation for doSomething() method

6. Testing our Bean

Now that our bean is written, we need to deploy, run and test it. The deploying and running step is done by using MyEclipse to deploy the bean to a Java EE 5.0 compliant application server, for this tutorial we are using Glassfish 2. After our bean is deployed, we will write a simple Java class that will load our EJB3 using JNDI, and call it's doSomething() method.

Deploying the Bean

First, assuming you have Glassfish 2 setup, you can quickly deploy the project by using the MyEclipse Deployment Tool:

Then make sure the project is selected, and click Add to add a new deployment for the project to Glassfish 2:

On the new deployment dialog, make sure to select the app server you want to deploy the bean to (must be Java EE 5.0 compliant for the purposes of this tutorial) and hit Finish:

Confirm that the deployment was successful and hit OK:

Now that our EJB is deployed, we can start the application server up before writing our simple test case. First click the Application Server launch drop down to select the app server to start:

Then the application server will start up, and likely print messages to the console about successfully deploying the Session Bean:

At this point, we are ready to write our test class that will call the EJB.

Testing the Bean

To start, we need to create a new Java class in our package to test our bean with:

Then name the test class and tell MyEclipse to generate a main method for it:

Before we are ready to add code to our client and run it, we need to add appserver-rt.jar to our Build Path. This JAR is from the Glassfish 2 library directory and contains a customized jndi.properties file that will allow us to connect directly to the Glassfish 2 JNDI context automatically and retrieve our bean with almost no effort. So let's add that JAR now:

Then switch to the Libraries tab, and click Add External JAR to find the JAR and add it:

Drill down into the Glassfish 2 install directory, then into the /lib directory and select the appserver-rt.jar file and add it:

After it's added, hit OK:

Now we are ready to add code to our test client and run it. The actual code, thanks to the JAR we just added, is surprisingly simple:

public static void main(String[] args) {
try {
InitialContext ctx = new InitialContext();
MyBeanRemote bean = ( MyBeanRemote) ctx.lookup(" com.myeclipseide.ejb3.MyBeanRemote");
bean.doSomething();
} catch (NamingException e) {
e.printStackTrace();
}
}

Session Bean Test Client Code

There are two key things to notice in the code above to make sense of it:

  1. We cast the returned bean not to MyBean but to the interface MyRemoteBean because we are requesting the remote bean from the JNDI context. As mentioned above, the methods exposed by the different Local/Remote interfaces could vary, so we need to stick to the interface we are requesting.
  2. Glassfish uses a default JNDI name-binding for EJBs that don't specify one. If you scroll back up to the server-log screenshot, you'll notice that the default name is printed out in the log. This default name is different from application to application server, and most folks would use mappedName value of the @Stateless annotation to specify a new binding across all app servers. For example: @Stateless(name="MyBean", mappedName="ejb/MyBean")
  3. Once we have the bean, we can treat it like a local instance, and simply invoke it.

Because of how we wrote the code for our bean ( System.out.println) the result of #3 is output to the application server console in MyEclipse:

Our test client worked!

7. Conclusion

In this tutorial we took a look at how Stateless Session Bean development worked in MyEclipse using the new EJB3 annotations and technology in Java EE 5.0. Another important part of EJB3 are the EJB Entity Beans. Fortunately using EJB3 Entity Beans is almost identical to using JPA Entities; both of which MyEclipse can reverse-engineer for you into your project. If you are interested in learning about JPA/EJB3 Entities, please check out the MyEclipse JPA Tutorial.

If you have any suggestions for us to help make it more informative, please let us know.

Below we would like to provide you with some more information pertaining to the topic covered in this tutorial. We offer the FAQ section for quick references to common questions and the Resources section with links to other helpful resources online that you may want to become familiar. We realize we can't cover every question you may have in one tutorial, but between this tutorial contents and our additional learning resources we hope you are far on your way to feeling comfortable with the technology.

9. Resources

In this section we want to provide you with additional links to resources that supplement the topics covered in this tutorial. While this is not an exhaustive list, we do make an effort to point to the more popular links that should provide you with diverse, high-quality information.

  • Sample EJB3 Project for This Tutorial
  • List of Many Glassfish / EJB3 Tutorials and Tips
  • Glassfish EJB3 FAQ

Click here to View more...