Over 70 highly focused practical recipes to maximize your output with NetBeans
Enterprise Java Beans (EJB) is a framework of server-side components that encapsulates business logic.
These components adhere to strict specifications on how they should behave. This ensures that vendors who wish to implement EJB-compliant code must follow conventions, protocols, and classes ensuring portability.
The EJB components are then deployed in EJB containers, also called application servers, which manage persistence, transactions, and security on behalf of the developer.
If you wish to learn more about EJBs, visit http://jcp.org/en/jsr/detail?id=318 or https://www.packtpub.com/developer-guide-for-ejb3/book.
For our EJB application to run, we will need the application servers. Application servers are responsible for implementing the EJB specifications and creating the perfect environment for our EJBs to run in.
Some of the capabilities supported by EJB and enforced by Application Servers are:
NetBeans 6.9, or higher, supports the new Java EE 6 platform, making it the only IDE so far to bring the full power of EJB 3.1 to a simple IDE interface for easy development.
NetBeans makes it easy to develop an EJB application and deploy on different Application Servers without the need to over-configure and mess with different configuration files. It's as easy as a project node right-click.
In this recipe, we will see how to create an EJB project using the wizards provided by NetBeans.
It is required to have NetBeans with Java EE support installed to continue with this recipe.
If this particular NetBeans version is not available in your machine, then you can download it from http://download.netbeans.org.
There are two application servers in this installation package, Apache Tomcat or GlassFish, and either one can be chosen, but at least one is necessary.
In this recipe, we will use the GlassFish version that comes together with NetBeans 7.0 installation package.
The new project structure is created.
NetBeans creates a complete file structure for our project.
It automatically configures the compiler and test libraries and creates the GlassFish deployment descriptor.
The deployment descriptor filename specific for the GlassFish web server is glassfish-web.xml.
The Java Persistence API (JPA) is one of the frameworks that equips Java with object/relational mapping. Within JPA, a query language is provided that supports the developers abstracting the underlying database.
With the release of JPA 2.0, there are many areas that were improved, such as:
We are not going to study the inner workings of JPA in this recipe. If you wish to know more about JPA, visit http://jcp.org/en/jsr/detail?id=317 or http://download.oracle.com/javaee/5/tutorial/doc/bnbqa.html.
NetBeans provides very good support for enabling your application to quickly create entities annotated with JPA.
In this recipe, we will see how to configure your application to use JPA. We will continue to expand the previously-created project.
We will use GlassFish Server in this recipe since it is the only server that supports Java EE 6 at the moment.
We also need to have Java DB configured. GlassFish already includes a copy of Java DB in its installation folder. Another source of installed Java DB is the JDK installation directory.
It is not necessary to build on top of the previous recipe, but it is imperative to have a database schema. Feel free to create your own entities by following the steps presented in this recipe.
NetBeans then imports and creates our Java class from the database schema, in our case the Manufacturer.java file placed under the entities package.
Besides that, NetBeans makes it easy to import and start using the entity straightaway. Many of the most common queries, for example find by name, find by zip, and find all, are already built into the class itself.
The JPA queries, which are akin to normal SQL queries, are defined in the entity class itself. Listed below are some of the queries defined in the entity class Manufacturer.java:
@Entity
@Table(name = "MANUFACTURER")
@NamedQueries({
@NamedQuery(name = "Manufacturer.findAll", query = "SELECT m FROM
Manufacturer m"),
@NamedQuery(name = "Manufacturer.findByManufacturerId", query
= "SELECT m FROM Manufacturer m WHERE m.manufacturerId =
:manufacturerId"),
The @Entity annotation defines that this class, Manufacturer.java, is an entity and when followed by the @Table annotation, which has a name parameter, points out the table in the Database where the information is stored.
The @NamedQueries annotation is the place where all the NetBeans-generated JPA queries are stored. There can be as many @NamedQueries as the developer feels necessary. One of the NamedQueries we are using in our example is named Manufacturer.findAll, which is a simple select query. When invoked, the query is translated to:
SELECT m FROM Manufacturer m
On top of that, NetBeans implements the equals, hashCode, and toString methods. Very useful if the entities need to be used straight away with some collections, such as HashMap.
Below is the NetBeans-generated code for both hashCode and the toString methods:
@Override
public int hashCode() {
int hash = 0;
hash += (manufacturerId != null ? manufacturerId.hashCode() :
0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id
fields are not set
if (!(object instanceof Manufacturer)) {
return false;
}
Manufacturer other = (Manufacturer) object;
if ((this.manufacturerId == null && other.manufacturerId
!= null) || (this.manufacturerId != null && !this.manufacturerId.
equals(other.manufacturerId))) {
return false;
}
return true;
}
NetBeans also creates a persistence.xml and provides a Visual Editor, simplifying the management of different Persistence Units (in case our project needs to use more than one); thereby making it possible to manage the persistence.xml without even touching the XML code. A persistence unit, or persistence.xml, is the configuration file in JPA which is placed under the configuration files, when the NetBeans view is in Projects mode. This file defines the data source and what name the persistence unit has in our example:
<persistence-unit name="EJBApplicationPU" transaction-type="JTA">
<jta-data-source>jdbc/sample</jta-data-source>
<properties/>
</persistence-unit>
The persistence.xml is placed in the configuration folder, when using the Projects view. In our example, our persistence unit name is EJBApplicationPU, using the jdbc/sample as the data source.
To add more PUs, click on the Add button that is placed on the uppermost right corner of the Persistence Visual Editor.
This is an example of adding another PU to our project:
A Session Bean encapsulates business logic in methods, which in turn are executed by a client. This way, the business logic is separated from the client.
Stateless Session Beans do not maintain state. This means that when a client invokes a method in a Stateless bean, the bean is ready to be reused by another client. The information stored in the bean is generally discarded when the client stops accessing the bean.
This type of bean is mainly used for persistence purposes, since persistence does not require a conversation with the client.
It is not in the scope of this recipe to learn how Stateless Beans work in detail. If you wish to learn more, please visit: http://jcp.org/en/jsr/detail?id=318 or https://www.packtpub.com/developer-guide-for-ejb3/book
In this recipe, we will see how to use NetBeans to create a Stateless Session Bean that retrieves information from the database, passes through a servlet and prints this information on a page that is created on-the-fly by our servlet.
It is required to have NetBeans with Java EE support installed to continue with this recipe.
If this particular NetBeans version is not available in your machine, please visit http://download.netbeans.org.
We will use the GlassFish Server in this recipe since it is the only Server that supports Java EE 6 at the moment.
We also need to have Java DB configured. GlassFish already includes a copy of Java DB in its installation folder.
It is possible to follow the steps on this recipe without the previous code, but for better understanding we will continue to build on the top of the previous recipes source code.
Here are the steps for us to create business methods:
@PersistenceUnit
EntityManagerFactory emf;
public List findAll(){
return emf.createEntityManager().createNamedQuery("Manufacturer.
findAll").getResultList();
}
java.util.List; javax.persistence.EntityManagerFactory; javax.persistence.PersistenceUnit;
Creating the Servlet:
With the ManufacturerServlet open:
After the class declaration and before the processRequest method, add:
@EJB ManufacturerEJB manufacturerEJB;
Then inside the processRequest method, first line after the try statement, add:
List<Manufacturer> l = manufacturerEJB.findAll();
Remove the /* TODO output your page here and also */.
And finally replace:
out.println("<h1>Servlet ManufacturerServlet at " + request. getContextPath () + "</h1>");
With:
for(int i = 0; i < 10; i++ )
out.println("<b>City</b>"+ l.get(i).getCity() +", <b>State</b>"+
l.get(i).getState() +"<br>" );
Resolve all the import errors and save the file.
To execute the code produced in this recipe, right-click on the EJBApplication node and select Run.
When the browser launches append to the end of the URL/ManufacturerServlet, hit Enter.
Our application will return City and State names.
One of the coolest features in Java EE 6 is that usage of web.xml can be avoided if annotating the servlet. The following code does exactly that:
@WebServlet(name="ManufacturerServlet", urlPatterns={"/ ManufacturerServlet"})
Since we are working on Java EE 6, our Stateless bean does not need the daunting work of creating interfaces, the @Stateless annotation takes care of that, making it easier to develop EJBs.
We then add the persistence unit, represented by the EntityManagerFactory and inserted by the @PersistenceUnit annotation.
Finally we have our business method that is used from the servlet. The findAll method uses one of the named queries from our entity to fetch information from the database.