Advanced Java® EE Development With WildFly® - Sample Chapter
Advanced Java® EE Development With WildFly® - Sample Chapter
$ 49.99 US
32.99 UK
P U B L I S H I N G
Deepak Vohra
Advanced Java EE
Development with WildFly
Advanced Java EE
Development with WildFly
ee
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
Advanced Java EE
Development with WildFly
Your one-stop guide to developing Java EE applications with
the Eclipse IDE, Maven, and WildFly 8.1
Sa
m
Deepak Vohra
Advanced Java EE
Development with WildFly
WildFly is the new name for JBoss Application Server (JBoss AS) starting with version
8.0.0. WildFly provides high startup speed, low memory overhead, a high-performance,
scalable web server, customizable runtime based on pluggable subsystems, and support
for Java EE 7 and the latest web development standards. In past references to the server,
"JBoss" is still used, but for subsequent references, "WildFly" is used. According to the
Developer Productivity Report 2012, referred to subsequently as the "2012 report", JBoss
is the most commonly used application server, with 28 percent of Java developers or
organizations using the application server, more than any other application server. The
same report indicated that 67 percent of Java developers use the Maven build tool, more
than any other build tool. Eclipse is used by 68 percent of Java developers. The Java
Tools and Technologies Landscape for 2014 report (referred to subsequently as the
"2014 report") indicates that JBoss is the most commonly used application server in
both development (16 percent) and production (17 percent). In the book, we discuss
developing Java EE applications using WildFly 8.1.0, Maven 3, and Eclipse IDE.
The book combines the most commonly used tools for Java EE development: WildFly,
Maven, and Eclipse IDE.
The book is based on the Java EE standards 5, 6, and 7. We will discuss the
commonly used technologies and frameworks JAX-RS 1.1, JSF 2.0, JPA 2.0,
JAX-WS 2.2, EJB 3.0, Hibernate 4, Ajax, GWT 2.4, and Spring 3.1. The new
Java EE7 support for JAX-RS 2.0 is discussed with RESTEasy. The new Java EE 7
feature for processing JSON is also discussed.
While several books on WildFly administration are available, none on Java EE
application development with WildFly are available. WildFly is the most commonly used
application server with support for all the commonly used Java EE technologies and
frameworks. WildFly is efficient, lightweight, and modular, and provides a flexible
deployment structure. JBoss Tools provides a set of plugins with support for WildFly,
Maven, and Java EE frameworks such as JSF. Maven is the most commonly used build
tool for compiling and packaging a Java EE application based on a project-object model
(POM). Maven provides dependency management. The Eclipse IDE for Java EE
developers is the most commonly used Java EE IDE.
The objective of the book is to discuss how a Java EE developer would develop
applications with WildFly using Maven as the build tool and Eclipse IDE as the
development environment. The book covers all aspects of application development,
including the following topics:
In Chapter 9, Using JAX-RS 2.0 in Java EE 7 with RESTEasy, we introduce the support
for JAX-RS 2.0: the Java API for RESTful Web Services added to Java EE 7. We discuss
the new Client API introduced in JAX-RS 2.0. We also discuss the asynchronous
processing feature of JAX-RS 2.0.
In Chapter 10, Processing JSON with Java EE 7, we introduce another new feature
in Java EE 7, that is, the support for JSR 353: Java API for JSON Processing.
Creating entities
https://www.eclipse.org/downloads/packages/release/Luna/SR1.
apache.org/download.cgi.
[2]
Chapter 1
[3]
In WildFly Application Server 8.x, which appears below New Server Runtime
Environment, specify a Name for the new runtime or choose the default name,
which is WildFly 8.x Runtime. Select the Home Directory for the WildFly 8.x
server using the Browse button. The Home Directory is the directory where WildFly
8.1 is installed. The default path is C:\wildfly-8.1.0.Final for this chapter and
subsequent chapters. Select the Runtime JRE as JavaSE-1.7. If the JDK location
is not added to the runtime list, first add it from the JRE preferences screen in
Eclipse. In Configuration base directory, select standalone as the default setting. In
Configuration file, select standalone.xml as the default setting. Click on Finish:
[4]
Chapter 1
A new server runtime environment for WildFly 8.x Runtime gets created, as shown
in the following screenshot. Click on OK:
[5]
Creating a Server Runtime Environment for WildFly 8.x is not a prerequisite for
creating a Java EE project in Eclipse. In the next section, we will create a new
Java EE project for an EJB 3.x application.
The Java EE EAR Project wizard gets started. By default, a Java EE 6 project is
created. A Java EE EAR Project is a Maven project. The New Project Example
window lists the requirements and runs a test for the requirements. The JBoss AS
runtime is required and some plugins (including the JBoss Maven Tools plugin) are
required for a Java EE project. Select Target Runtime as WildFly 8.x Runtime,
which was created in the preceding section. Then, check the Create a blank project
checkbox. Click on the Next button:
[6]
Chapter 1
Specify Project name as jboss-ejb3, Package as org.jboss.ejb3, and tick the Use
default Workspace location box. Click on the Next button:
[7]
[8]
Chapter 1
A Java EE project gets created, as shown in the following Project Explorer window.
Delete the jboss-ejb3/jboss-ejb3-ear/src/main/application/META-INF/
jboss-ejb3-ds.xml configuration file. The jboss-ejb3 project consists of three
subprojects: jboss-ejb3-ear, jboss-ejb3-ejb, and jboss-ejb3-web. Each
subproject consists of a pom.xml file for Maven. Initially the subprojects indicate
errors with red error markers, but these would get fixed when the main project is
built later in the chapter. Initially the subprojects might indicate errors with red error
markers, but these would get fixed when the main project is built later in the chapter.
We will configure a data source with the MySQL database in a later section. The
jboss-ejb3-ejb subproject consists of a META-INF/persistence.xml file within the
src/main/resources source folder for the JPA database persistence configuration.
We will use MySQL as the database for data for the EJB application. In the next
section, we will create a data source in the MySQL database.
[9]
[ 10 ]
Chapter 1
[ 11 ]
6. In the login dialog box, specify the username and password for the user
added with the add-user.bat script.
7. Select the Runtime tab in Administration Console. The MySQL datasource
is listed as deployed in Datasources Subsystems, as shown in the following
screenshot. Click on Test Connection to test the connection:
[ 12 ]
Chapter 1
In the next section, we will create entities for the EJB 3.x application.
[ 13 ]
Creating entities
In EJB 3.x, an entity is a POJO (Plain Old Java Object) persistent domain object that
represents a database table row. As an entity is a Java class, create a Java class in the
jboss-ejb3-ejb subproject of the jboss-ejb3 project. Select File | New. In the New
window, select Java | Class and click on Next:
[ 14 ]
Chapter 1
Similarly, add Java classes for the Edition.java, Section.java, and Article.java
entities, as shown in the following Project Explorer:
[ 15 ]
Next, we develop the EJB 3.x entities. A JPA persistence provider is required for
the EJB entities, and we will use the Hibernate persistence provider. The Hibernate
persistence provider has some peculiarities that need to be mentioned, as follows:
If an entity has more than one non-lazy association of the following types,
Hibernate fails to fetch the entity:
We will develop the Catalog, Edition, Section, and Article class with one-to-many
relationship between the Catalog and Edition class, the Edition and Section class,
and the Section and Article class, as shown in the following UML class diagram:
Annotate the Catalog entity class with the @Entity annotation and the @Table
annotation. If the @Table annotation is not used, then the entity name is used as
the table name by default. In the @Table annotation, specify the table name as
CATALOG and uniqueConstraints, using the @UniqueConstraint annotation for the
id column. Specify the named queries as findCatalogAll, which selects all Catalog
and findCatalogByJournal entities. This selects a Catalog entity by Journal, using the
@NamedQueries and @NamedQuery annotations:
@Entity
@Table(name = "CATALOG", uniqueConstraints = @
UniqueConstraint(columnNames = "ID"))
@NamedQueries({
@NamedQuery(name="findCatalogAll", query="SELECT c FROM Catalog c"),
@NamedQuery(name="findCatalogByJournal",
[ 16 ]
Chapter 1
query="SELECT c FROM Catalog c WHERE c.journal = :journal")
})
public class Catalog implements Serializable {
}
fetch element is set to EAGER. With EAGER fetching the associated entity, collection is
[ 17 ]
annotation, a join table is included on the owning side to initiate cascade operations.
The join columns are specified using the @JoinColumn annotation. The Edition.
java entity class is available in the code download for the chapter.
Develop the entity class for the SECTION table: Section.java. Specify the
findSectionAll and findSectionBySectionName named queries to find Section
entities. Specify the id and sectionname bean properties. Specify the bi-directional
many-to-one association to Edition using the @ManyToOne annotation and the bidirectional one-to-many association to Article using @OneToMany. The @JoinTable
and @JoinColumn are specified only for the @ManyToOne association for which
Section is the owning side. The Section.java entity class is available in the code
download for the chapter.
Specify the entity class for the ARTICLE table: Article.java. The Article entity
is mapped to the ARTICLE database table using the @TABLE annotation. Add the
findArticleAll and findArticleByTitle named queries to find Article entities.
Specify id and sectionname bean properties and the associated get/set methods.
The Article entity is the owning side of the bi-directional many-to-one association
to Section. Therefore, the @JoinTable and @JoinColumn are specified. The
Article.java class is available in the code downloaded for the chapter.
[ 18 ]
Chapter 1
[ 19 ]
The JPA specification does not mandate a persistence provider to create tables with
the hibernate.hbm2ddl.auto property set to create-drop or create. Hibernate
persistence provider supports creating tables. In addition to the entity tables, some
additional tables (such as the join tables and the sequence table) are created by the
Hibernate persistence provider.
[ 20 ]
Chapter 1
In the bean session, we use an EntityManager to create, remove, find, and query
persistence entity instances. Inject a EntityManager using the @PersistenceContext
annotation. Specify the unitName as the unitName configured in persistence.
xml. Next, specify the getAllEditions, getAllSections, getAllArticles,
getAllCatalogs get methods to fetch the collection of entities. The get methods
get all entities' collections with the named queries specified in the entities.
The createNamedQuery method of EntityManager is used to create a Query
object from a named query. Specify the TransactionAttribute annotation's
TransactionAttributeType enumeration to REQUIRES_NEW, which has the
advantage that if a transaction is rolled back due to an error in a different transaction
context from which the session bean is invoked, it does not affect the session bean.
To demonstrate the use of the entities, create the test data with the createTestData
convenience method in the session bean. Alternatively, a unit test or an extension
class can also be used. Create a Catalog entity and set the journal using the
setJournal method. We do not set the id for the Catalog entity as we use the
GenerationType.AUTO generation strategy for the ID column. Persist the entity
using the persist method of the EntityManager object. However, the persist
method does not persist the entity to the database. It only makes the entity instance
managed and adds it to the persistence context. The EntityManager.flush()
method is not required to be invoked to synchronize the entity with the database as
EntityManager is configured with FlushModeType as AUTO (the other setting being
COMMIT) and a flush will be done automatically when the EntityManager.persist()
is invoked:
Catalog catalog1 = new Catalog();
catalog1.setJournal("Oracle Magazine");
em.persist(catalog1);
Similarly, create and persist an Edition entity object. Add the Catalog object:
catalog1 using the setCatalog method of the Edition entity class:
Edition edition = new Edition();
edition.setEdition("January/February 2009");
edition.setCatalog(catalog1);
em.persist(edition);
[ 21 ]
Likewise add the Section and Article entity instances. Add another Catalog
object, but without any associated Edition, Section, or Article entities:
Catalog catalog2 = new Catalog();
catalog2.setJournal("Linux Magazine");
em.persist(catalog2);
Next, we will delete data with the deleteSomeData method, wherein we first create
a Query object using the named query findCatalogByJournal. Specify the journal
to delete with the setParameter method of the Query object. Get the List result
with the getResultList method of the Query object. Iterate the List result and
remove the Catalog objects with the remove method of the EntityManager object.
The remove method only removes the Catalog object from the persistence context:
public void deleteSomeData() {
// remove a catalog
Query q = em.createNamedQuery("findCatalogByJournal");
//q.setParameter("journal", "Linux Magazine");
q.setParameter("journal", "Oracle Magazine");
List<Catalog> catalogs = q.getResultList();
for (Catalog catalog : catalogs) {
em.remove(catalog);
}
}
[ 22 ]
Chapter 1
[ 23 ]
Description
java:module
java:app
java:global
When the jboss-ejb3 application is deployed, the JNDI bindings in the namespaces
(discussed in the preceding table) are created as indicated by the server message:
JNDI bindings for session bean named CatalogSessionBeanFacade in
deployment unit subdeployment "jboss-ejb3-ejb.jar" of deployment
"jboss-ejb3-ear.ear" are as follows:
java:global/jboss-ejb3-ear/jboss-ejb3-ejb/
CatalogSessionBeanFacade!org.jboss.ejb3.model.CatalogSessionBeanFacade
java:app/jboss-ejb3-ejb/CatalogSessionBeanFacade!org.jboss.ejb3.
model.CatalogSessionBeanFacade
java:module/CatalogSessionBeanFacade!org.jboss.ejb3.model.
CatalogSession
[ 24 ]
Chapter 1
BeanFacade
java:global/jboss-ejb3-ear/jboss-ejb3-ejb/CatalogSessionBeanFacade
java:app/jboss-ejb3-ejb/CatalogSessionBeanFacade
java:module/CatalogSessionBeanFacade
Using the local JNDI name lookup in the java:app namespace ,retrieve the
CatalogSessionBeanFacade component:
CatalogSessionBeanFacade bean = (CatalogSessionBeanFacade) context
.lookup("java:app/jboss-ejb3-ejb/CatalogSessionBeanFacade!org.jboss.
ejb3.model.CatalogSessionBeanFacade");
Invoke the createTestData method and retrieve the List Catalog entities. Iterate
over the Catalog entities and output the catalog ID as the journal name:
bean.createTestData();
List<Catalog> catalogs = beanRemote.getAllCatalogs();
out.println("<br/>" + "List of Catalogs" + "<br/>");
for (Catalog catalog : catalogs) {
out.println("Catalog Id:");
out.println("<br/>" + catalog.getId() + "<br/>");
out.println("Catalog Journal:");
out.println(catalog.getJournal() + "<br/>");
}
Similarly, obtain the Entity, Section, and Article entities and output the entity
property values. The catalog.jsp file is available in the code downloaded for
the chapter.
[ 25 ]
The ejb, web, and ear modules can be built and installed individually using
subproject-specific pom.xml, or these can be built together using the pom.xml file in
the jboss-ejb3 project. If built individually, the ejb module has to be built and
installed before the web module, as the web module has a dependency on the ejb
module. The ear module is to be built after the web and ejb modules have been built
and installed. We will build and install the top level project using the pom.xml file
in the jboss-ejb3 project, which has dependency specified on the jboss-ejb3-web
and jboss-ejb3-ejb artifacts. The pom.xml file for the jboss-ejb3-ejb subproject
specifies packaging as ejb. The WildFly 8.x provides most of the APIs required for an
EJB 3.x application. The provided APIs are specified with scope set to provided in
pom.xml. Dependencies for the EJB 3.1 API and the JPA 2.0 API are pre-specified. Add
the following dependency for the Hibernate Annotations API:
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.1_spec</artifactId>
<version>1.0.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
[ 26 ]
Chapter 1
The Maven POM.xml file for the EJB subproject is available in the code downloaded
for the chapter.
The pom.xml file for the subproject pre-specifies most of the required dependencies.
It also specifies dependency on the jboss-ejb3-ejb artifact:
<dependency>
<groupId>org.jboss.ejb3</groupId>
<artifactId>jboss-ejb3-ejb</artifactId>
<type>ejb</type>
<version>1.0.0</version>
<scope>provided</scope>
</dependency>
[ 27 ]
The EJB 3.1 API, the JPA 2.0 API, the JSF 2.1 API, and the JAX-RS 1.1 API are
provided by the WildFly 8.x server, as indicated by the provided scope in the
dependency declarations. Add the dependency on the hibernate-annotations
artifact. The build is preconfigured with the Maven WAR plugin, which is required
to package the subproject into an WAR file:
<?xml version="1.0" encoding="UTF-8"?>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<!-- Java EE 6 doesn't require web.xml, Maven needs to catch
up! -->
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
The pom.xml file for the jboss-ejb3-web subproject is available in the code
downloaded for the chapter.
The pom.xml file specifies dependency on the ejb and web modules:
<dependencies>
<!-- Depend on the ejb module and war so that we can package them
-->
<dependency>
<groupId>org.jboss.ejb3</groupId>
[ 28 ]
Chapter 1
<artifactId>jboss-ejb3-web</artifactId>
<version>1.0.0</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.jboss.ejb3</groupId>
<artifactId>jboss-ejb3-web</artifactId>
<version>1.0.0</version>
<type>war</type>
</dependency>
</dependencies>
The build tag in the pom.xml file specifies the configuration for the maven-earplugin plugin with output directory as the deployments directory in the WildFly
8.x standalone server. The EAR file generated from the Maven project is deployed
to the directory specified in the <outputDirectory/> element. Specify the
<outputDirectory/> element as the C:\wildfly-8.1.0.Final\standalone\
deployments directory. The outputDirectory might need to be modified based
on the installation directory of WildFly 8.1. The EAR, WAR, and JAR modules in the
deployments directory get deployed to the WildFly automatically, if the server
is running:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-ear-plugin</artifactId>
<version>2.8</version>
<configuration>
<!-- Tell Maven we are using Java EE 6 -->
<version>6</version>
<!-- Use Java EE ear libraries as needed. Java EE ear libraries
are in easy way to package any libraries needed in the ear, and
automatically have any modules (EJB-JARs and WARs) use them -->
<defaultLibBundleDir>lib</defaultLibBundleDir>
<fileNameMapping>no-version</fileNameMapping>
<outputDirectory>C:\wildfly-8.1.0.Final\standalone\deployments</
outputDirectory>
</configuration>
</plugin>
[ 29 ]
The pom.xml for the jboss-ejb3 project specifies dependency on the jboss-ejb3web and jboss-ejb3-ejb artifacts:
<dependency>
<groupId>org.jboss.ejb3</groupId>
<artifactId>jboss-ejb3-ejb</artifactId>
<version>${project.version}</version>
<type>ejb</type>
</dependency>
<dependency>
<groupId>org.jboss.ejb3</groupId>
<artifactId>jboss-ejb3-web</artifactId>
<version>${project.version}</version>
<type>war</type>
<scope>compile</scope>
</dependency>
Next, we will build and deploy the EAR module to WildFly 8.x while the server is
running. Right-click on pom.xml for the jboss-ejb3 Maven project and select Run
As | Maven install, as shown in the following screenshot:
[ 30 ]
Chapter 1
As the output from the pom.xml indicates all the three modules: ejb, web, and ear
get built. The ear module gets copied to the deployments directory in WildFly 8.x:
[ 31 ]
Start the WildFly 8.x server if not already started. The jboss-ejb3.ear file gets
deployed to the WildFly 8.x server and the jboss-ejb3-web context gets registered.
The jboss-ejb3.ear.deployed file gets generated in the deployments directory,
as shown in the following screenshot:
The EntityManager em persistence unit gets registered and the JNDI bindings for
the CatalogSessionBeanFacade session bean gets generated:
Starting Persistence Unit (phase 1 of 2) Service 'jboss-ejb3-ear.ear/
jboss-e
jb3-ejb.jar#em'
12:30:32,047 INFO [org.hibernate.jpa.internal.util.LogHelper]
(ServerService Th
read Pool -- 50) HHH000204: Processing PersistenceUnitInfo [
name: em
...]
The MySQL database tables for the entities get created, as shown in the following
screenshot:
[ 32 ]
Chapter 1
[ 33 ]
Chapter 1
<url>https://repository.jboss.org/nexus/content/groups/public/
</url>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-7.0</artifactId>
<version>1.0.0.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
In addition the pom.xml for the ejb module and web module subprojects should
specify the dependencies for the EJB 3.2, JSF 2.2, Servlet 3.1, and Hibernate JPA 2.1
specifications, as required, instead of the dependencies for the EJB 3.1, JSF 2.1, Servlet
3.0, and Hibernate JPA 2.0:
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.servlet</groupId>
<artifactId>jboss-servlet-api_3.1_spec</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.faces</groupId>
<artifactId>jboss-jsf-api_2.2_spec</artifactId>
<scope>provided</scope>
</dependency>
[ 35 ]
Summary
In this chapter, we used the JBoss Tools plugin 4.2 in Eclipse Luna to generate a
Java EE project for an EJB 3.x application in Eclipse IDE for Java EE Developers. We
created entities to create a Catalog and used the Hibernate persistence provider
to map the entities to the MySQL 5.6 database. Subsequently, we created a session
bean faade for the entities. In the session bean, we created a catalog using the
EntityManager API. We also created a JSP client to invoke the session bean facade
using the local JNDI lookup and subsequently invoke the session bean methods to
display database data. We used Maven to build the EJB, Web, and EAR modules and
deploy the EAR module to WildFly 8.1. We ran the JSP client in a browser to fetch
and display the data from the MySQL database. In the next chapter, we will discuss
another database persistence technology: Hibernate.
[ 36 ]
www.PacktPub.com
Stay Connected: