Maven
Maven
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 1
JAVA Means DURGASOFT
MAVEN
CONTENT:
1. Maven Overview
2. Maven
3. Maven Origins
4. What Maven Provide?
5. Mavens Principles
6. Declarative Execution
i) Maven's project object model (POM)
ii) Maven's build life cycle
7. Coherent Organization of Dependencies
i) Local Maven repository
ii) Central Maven repository
iii) Remote Maven Repository
iv) Locating dependency artifacts
8. Maven's Benefits
9. Maven Environment SetUp
i)System Requirement
ii)java installation verification
ii)set JAVA environment
iii)Download Maven Archive
iv) Extract Maven Archive and Configure Maven Environment Variables
vi) Add Maven bin directory location to system path and verify Maven installaton
10. Create Java Project
11. Build and Test Java Project
12. External Dependencies
13. Maven 2 Eclipse Plugin
14. Create web application using maven
15. Generate Documentation for Maven Project
16. Project Creation from Maven Templates
17. Team Collaboration with Maven
18. Migrating to Maven
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 2
JAVA Means DURGASOFT
Maven Overview:
Maven:
Maven is a project management framework. Maven is a build tool or a scripting framework.
Maven encompasses a set of build standards, an artifact repository
model, and a software engine that manages and describes projects. It defines a standard life cycle for
building, testing, and deploying project artifacts. It provides a framework that enables easy reuse of
common build logic for all projects following Maven's standards. The Maven project at the Apache
Software Foundation is an open source community which produces software tools that understand a
common declarative Project Object Model (POM).
Maven 2, a framework that greatly simplifies the process of managing a software project.
Note: Maven is a declarative project management tool that decreases your overall time
to market by effectively leveraging cross-project intelligence. It simultaneously reduces your
duplication effort and leads to higher code quality.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 3
JAVA Means DURGASOFT
Maven Origin’s:
Maven was borne of the practical desire to make several projects at the Apache Software
Foundation (ASF) work in the same, predictable way. Prior to Maven, every project at the ASF
had a different approach to compilation, distribution, and Web site generation. The ASF was
effectively a series of isolated islands of innovation. While there were some common themes
across the separate builds, each community was creating its own build systems and there was no
reuse of build logic across projects. The build process for Tomcat was different than the build
process for Struts, and the Turbine developers had a different site generation process than the
Jakarta Commons developers.
This lack of a common approach to building software meant that every new project tended to
copy and paste another project's build system. Ultimately, this copy and paste approach to build
reuse reached a critical tipping point at which the amount of work required to maintain the
collection of build systems was distracting from the central task of developing high-quality
software. In addition, for a project with a difficult build system, the barrier to entry was
extremely high; projects such as Jakarta Taglibs had (and continue to have) a tough time
attracting developer interest because it could take an hour to configure everything in just the
right way. Instead of focusing on creating good component libraries or MVC frameworks,
developers were building yet another build system.
Maven entered the scene by way of the Turbine project, and it immediately sparked interest as a
sort of Rosetta Stone for software project management. Developers within the Turbine project
could freely move between subcomponents, knowing clearly how they all worked just by
understanding how one of the components worked. Once developers spent time learning how one
project was built, they did not have to go through the process again when they moved on to the
next project. Developers at the ASF stopped figuring out creative ways to compile, test, and
package software, and instead, started focusing on component development.
The same standards extended to testing, generating documentation, generating metrics and
reports, and deploying. If you followed the Maven Build Life Cycle, your project gained a build by
default. Soon after the creation of Maven other projects, such as Jakarta Commons, the
Codehaus community started to adopt Maven 1 as a foundation for project management.
Many people come to Maven familiar with Ant, so it's a natural association, but Maven is an
entirely different creature from Ant. Maven is not just a build tool, and not necessarily a
replacement for Ant.
Whereas Ant provides a toolbox for scripting builds, Maven provides standards and a set of
patterns in order to facilitate project management through reusable, common build strategies.
Maven Provides:
Maven provides developers to manage the following: Builds, Documentation, Reporting,
Dependencies, SCM's, Releases.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 4
JAVA Means DURGASOFT
Maven provides a useful abstraction for building software in the same way an automobile
provides an abstraction for driving. When you purchase a new car, the car provides a known
interface; if you've learned how to drive a Jeep, you can easily drive a Camry. Maven takes a
similar approach to
software projects: if you can build one Maven project you can build them all, and if you can apply
a
testing plugin to one project, you can apply it to all projects. You describe your project using
Maven's
model, and you gain access to expertise and best-practices of an entire industry.
Given the highly inter-dependent nature of projects in open source, Maven’s ability to standardize
locations for source files, documentation, and output, to provide a common layout for project
documentation, and to retrieve project dependencies from a shared storage area makes the
building
process much less time consuming, and much more transparent.
Maven provides you with:
A comprehensive model for software projects
Tools that interact with this declarative model
An individual Maven project's structure and contents are declared in a Project Object Model
(POM),
which forms the basis of the entire Maven system.
Maven Principles:
According to Christopher Alexander "patterns help create a shared language for communicating
insight and experience about problems and their solutions".
The following Maven principles were inspired by Christopher Alexander's idea of creating a shared
language:
Convention over configuration
Declarative execution
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 5
JAVA Means DURGASOFT
Declarative Execution:
Everything in Maven is driven in a declarative fashion using Maven's Project Object Model
(POM) and specifically, the plugin configurations contained in the POM. The execution of Maven's
plugins is coordinated by Maven's build life cycle in a declarative fashion with instructions from
Maven's POM.
Maven’s POM:
Maven is project-centric by design, and the POM is Maven's description of a single project.
Without the POM, Maven is useless - the POM is Maven's currency. It is the POM that drives
execution in Maven and this approach can be described as model-driven or declarative execution.
The POM is an XML document and looks like the following (very) simplified example:
<project>
<modelVersion>4.0.0</modelVersion>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 6
JAVA Means DURGASOFT
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
POM will allow you to compile, test, and generate basic documentation.
The POM contains every important piece of information about your project.
Maven's Super POM carries with it all the default conventions that Maven encourages, and is the
analog of the Java language's java.lang.Object class.
modelVersion - This required element indicates the version of the object model that the
POM is using. The version of the model itself changes very infrequently, but it is mandatory
in order to ensure stability when Maven introduces new features or other model changes.
groupId - This element indicates the unique identifier of the organization or group that
created the project. The groupId is one of the key identifiers of a project and is typically
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 7
JAVA Means DURGASOFT
based on the fully qualified domain name of your organization. For example
org.apache.maven.plugins is the designated groupId for all Maven plugins.
artifactId - This element indicates the unique base name of the primary artifact being
generated by this project. A typical artifact produced by Maven would have the form
<artifactId>-<version>.<extension> (for example, myapp-1.0.jar). Additional
artifacts such as source bundles also use the artifactId as part of their file name.
packaging - This element indicates the package type to be used by this artifact (JAR,
WAR, EAR, etc.). This not only means that the artifact produced is a JAR, WAR, or EAR,
but also indicates a specific life cycle to use as part of the build process. The life cycle is a
topic dealt with later in this chapter. For now, just keep in mind that the selected packaging
of a project plays a part in customizing the build life cycle. The default value for the
packaging element is jar so you do not have to specify this in most cases.
version - This element indicates the version of the artifact generated by the project.
Maven goes a long way to help you with version management and you will often see the
SNAPSHOT designator in a version, which indicates that a project is in a state of
development.
name - This element indicates the display name used for the project. This is often used in
Maven's generated documentation, and during the build process for your project, or other
projects that use it as a dependency.
url - This element indicates where the project's site can be found.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 8
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 9
JAVA Means DURGASOFT
When we execute mvn post-clean command, Maven invokes the clean lifecycle consisting of the
following phases.
pre-clean
clean
post-clean
Maven clean goal (clean:clean) is bound to the clean phase in the clean lifecycle. Its clean:clean
goal deletes the output of a build by deleting the build directory.
Thus when mvn clean command executes, Maven deletes the build directory.
We can customize this behavior by mentioning goals in any of the above phases of clean life
cycle.
This is the primary life cycle of Maven and is used to build the application. It has following 23
phases.
There are few important concepts related to Maven Lifecycles which are wroth to mention:
When a phase is called via Maven command,
Ex: mvn compile, only phases upto and including that phase will execute. Different maven goals
will be bound to different phases of Maven lifecycle depending upon the type of packaging (JAR /
WAR / EAR).
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 10
JAVA Means DURGASOFT
Site Lifecycle:
Maven Site plugin is generally used to create fresh documentation to create reports, deploy site
etc.
Phases:
pre-site
site
post-site
site-deploy
Profile Activation:
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 11
JAVA Means DURGASOFT
Maven Plugin’s:
Maven is actually a plugin execution framework where every task is actually done by plugins.
Maven Plugins are generally used to :
A plugin generally provides a set of goals and which can be executed using following syntax:
For example, a Java project can be compiled with the maven-compiler-plugin's compile-goal by
running following command.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 12
JAVA Means DURGASOFT
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
This POM states that your project has a dependency on JUnit, which is straightforward, but you may
be asking yourself “Where does that dependency come from?” and “Where is the JAR?” The answers
to those questions are not readily apparent without some explanation of how Maven's
dependencies,
artifacts and repositories work. In “Maven-speak” an artifact is a specific piece of software.
In Java, the most common artifact is a JAR file, but a Java artifact could also be a WAR, SAR, or EAR
file. A dependency is a reference to a specific artifact that resides in a repository. In order for Maven
to attempt to satisfy a dependency, Maven needs to know what repository to search as well as the
dependency's coordinates. A dependency is uniquely identified by the following identifiers: groupId,
artifactId and version.
At a basic level, we can describe the process of dependency management as Maven reaching out
into the world, grabbing a dependency, and providing this dependency to your software project.
There
is more going on behind the scenes, but the key concept is that Maven dependencies are declarative.
In the POM you are not specifically telling Maven where the dependencies are physically located, you
are simply telling Maven what a specific project expects.
Maven takes the dependency coordinates you provide in the POM, and it supplies these coordinates
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 13
JAVA Means DURGASOFT
to its own internal dependency mechanisms. With Maven, you stop focusing on a collection of JAR
files; instead you deal with logical dependencies. Your project doesn't require junit-3.8.1.jar,
instead it depends on version 3.8.1 of the junit artifact produced by the junit group. Dependency
Management is one of the most powerful features in Maven.
When a dependency is declared within the context of your project, Maven tries to satisfy that
dependency by looking in all of the remote repositories to which it has access, in order to find the
artifacts that most closely match the dependency request. If a matching artifact is located, Maven
transports it from that remote repository to your local repository for project use.
Repositories:
A maven repository is a place i.e. directory where all the project jars, library jar, plugins or any
other project specific artifacts are stored and can be used by Maven easily.
Maven repositories are of three types:
Local
Central
Remote
Local Repository:
Maven local repository is a folder location on your machine. It gets created when you run
any maven command for the first time.
Maven local repository keeps your project's all dependencies (library jars, plugin jars etc).
When you run a Maven build, then Maven automatically downloads all the dependency jars
into the local repository.
It helps to avoid references to dependencies stored on remote machine every time a
project is build.
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 14
JAVA Means DURGASOFT
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:/maven_repo</localRepository>
</settings>
When you run Maven command, Maven will download dependencies to your custom path.
Central Repository:
Maven central repository is repository provided by Maven community. It contains a large number
of commonly used libraries.
When Maven does not find any dependency in local repository, it starts searching in central
repository using following URL: http://repo1.maven.org/maven2/
To browse the content of central maven repository, maven community has provided a
URL:http://search.maven.org/#browse. Using this library, a developer can search all the
available libraries in central repository.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 15
JAVA Means DURGASOFT
Remote Repository:
Sometime, Maven does not find a mentioned dependency in central repository as well then it
stopped build process and output error message to console. To prevent such situation, Maven
provides concept of Remote Repository which is developer's own custom repository containing
required libraries or other project jars.
For example, using below mentioned POM.xml, Maven will download dependency (not available in
central repository) from Remote Repositories mentioned in the same pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.projectgroup</groupId>
<artifactId>project</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>com.companyname.common-lib</groupId>
<artifactId>common-lib</artifactId>
<version>1.0.0</version>
</dependency>
<dependencies>
<repositories>
<repository>
<id>companyname.lib1</id>
<url>http://download.companyname.org/maven2/lib1</url>
</repository>
<repository>
<id>companyname.lib2</id>
<url>http://download.companyname.org/maven2/lib2</url>
</repository>
</repositories>
</project>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 16
JAVA Means DURGASOFT
When we execute Maven build commands, Maven starts looking for dependency libraries in the
following sequence:
Step 1 - Search dependency in local repository, if not found, move to step 2 else if found
then do the further processing.
Step 3 - If a remote repository has not been mentioned, Maven simply stops the
processing and throws error (Unable to find dependency).
Maven Benefits:
Organizations and projects that adopt Maven benefit from:
Coherence: Maven allows organizations to standardize on a set of best practices. Because
Maven projects adhere to a standard model they are less opaque. The definition of this term
from the American Heritage dictionary captures the meaning perfectly: “Marked by an
orderly, logical, and aesthetically consistent relation of parts.“
Reusability: Maven is built upon a foundation of reuse. When you adopt Maven you are
effectively reusing the best practices of an entire industry.
Agility: Maven lowers the barrier to reuse not only for build logic, but also for software
components. Maven makes it is easier to create a component and then integrate it into a
multi-project build. Developers can jump between different projects without the steep
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 17
JAVA Means DURGASOFT
Maintainability: Organizations that adopt Maven can stop “building the build”, and focus
on
building the application. Maven projects are more maintainable because they follow a
common, publicly-defined model.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 18
JAVA Means DURGASOFT
To create your first project, you will use Maven's Archetype mechanism. An archetype is defined
as an original pattern or model from which all other things of the same kind are made. In Maven,
an archetype is a template of a project, which is combined with some user input to produce a
fully functional Maven project.
Archetype:
Archetype
Description
ArtifactIds
maven-archetype-
An archetype which contains a sample archetype.
archetype
maven-archetype-
An archetype which contains a simplifed sample J2EE application.
j2ee-simple
maven-archetype-
An archetype which contains a sample a sample Maven plugin.
mojo
maven-archetype-
An archetype which contains a sample Maven plugin.
plugin
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 19
JAVA Means DURGASOFT
maven-archetype-
An archetype which contains a sample Maven plugin site.
plugin-site
maven-archetype-
An archetype which contains a sample JSR-268 Portlet.
portlet
maven-archetype-
An archetype which contains a sample Maven project.
quickstart
maven-archetype-
An archetype which contains a simple Maven project.
simple
An archetype which contains a sample Maven site which demonstrates some
maven-archetype-
of the supported document types like APT, XDoc, and FML and demonstrates
site
how to i18n your site.
maven-archetype-
An archetype which contains a sample Maven site.
site-simple
maven-archetype-
An archetype which contains a sample Maven Webapp project.
webapp
First, you will notice that a directory named my-app has been created for the new project, and
this directory contains your pom.xml, which looks like the following:
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 20
JAVA Means DURGASOFT
One of the most powerful features in Maven is project inheritance. Using project inheritance
allows you to do things like state your organizational information, state your deployment
information, or state your common dependencies - all in a single place.
Being the observant user, you have probably taken a peek at all the POMs in each of the projects
that make up the Proficio project and noticed the following at the top of each of the POMs:
[...]
<parent>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
[...]
If you look at the top-level POM for Proficio, you will see that in the dependencies section there is
a declaration for JUnit version 3.8.1. In this case the assumption being made is that JUnit will be
used for testing in all our child projects. So, by stating the dependency in the top-level POM once,
you never have to declare this dependency again, in any of your child POMs. The dependency is
stated as following:
<project>
[...]
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
[...]
</project>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 21
JAVA Means DURGASOFT
What specifically happens for each child POM, is that each one inherits the dependencies section
of
the top-level POM. So, if you take a look at the POM for the proficio-core module you will see
the following (Note: there is no visible dependency declaration for JUnit):
<project>
<parent>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>proficio-core</artifactId>
<packaging>jar</packaging>
<name>Maven Proficio Core</name>
<dependencies>
<dependency>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio-api</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-container-default</artifactId>
</dependency>
</dependencies>
</project>
In order for you to see what happens during the inheritance process, you will need to use the
handy mvn help:effective-pom command.
This command will show you the final result for a target POM. After you move into the proficio-
core module directory and run the command, take a look at the resulting POM; you will see the
JUnit version 3.8.1 dependency:
POM.xml
<project>
[...]
<dependencies>
[...]
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
[...]
</dependencies>
[...]
</project>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 22
JAVA Means DURGASOFT
Managing Dependencies:
When you are building applications you typically have a number of dependencies to manage and
that number only increases over time, making dependency management difficult to say the least.
Maven's strategy for dealing with this problem is to combine the power of project inheritance with
specific dependency management elements in the POM.
When you write applications which consist of multiple, individual projects, it is likely that some of
those projects will share common dependencies. When this happens it is critical that the same
version of a given dependency is used for all your projects, so that the final application works
correctly.
You don't want, for example, to end up with multiple versions of a dependency on the classpath
when your application executes, as the results can be far from desirable. You want to make sure
that all the versions, of all your dependencies, across all of your projects are in alignment so that
your testing accurately reflects what you will deploy as your final result. In order to manage, or
align, versions of dependencies across several projects, you use the dependency management
section in the top-level POM of an application.
To illustrate how this mechanism works, let's look at the dependency management section of the
Proficio top-level POM:
<project>
[...]
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio-model</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio-store-memory</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio-store-xstream</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-container-default</artifactId>
<version>1.0-alpha-9</version>
</dependency>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 23
JAVA Means DURGASOFT
</dependencies>
</dependencyManagement>
[...]
</project>
Using Snapshots:
While you are developing an application with multiple modules, it is usually the case that each of
the modules are in flux. Your APIs might be undergoing some change or your implementations
are undergoing change and are being fleshed out, or you may be doing some refactoring. Your
build system needs to be able to deal easily with this real-time flux, and this is where Maven's
concept of a snapshot comes into play. A snapshot in Maven is an artifact that has been prepared
using the most recent sources available. If you look at the top-level POM for Proficio you will see
a snapshot version specified:
<project>
[...]
<version>1.0-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio-model</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.devzuz.mvnbook.proficio</groupId>
<artifactId>proficio-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-container-default</artifactId>
<version>1.0-alpha-9</version>
</dependency>
</dependencies>
</dependencyManagement>
[...]
</project>
Specifying a snapshot version for a dependency means that Maven will look for new versions
of that dependency without you having to manually specify a new version. Snapshot
dependencies are assumed to be changing, so Maven will attempt to update them. By default
Maven will look for snapshots on a daily basis, but you can use the -U command line option to
force the search for updates.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 24
JAVA Means DURGASOFT
Controlling Snapshots:
Snapshots were designed to be used in a team environment as a means for sharing development
versions of artifacts that have already been built. Usually, in an environment where a number of
modules are undergoing concurrent development, the build involves checking out all of the
dependent
projects and building them yourself. Additionally, in some cases, where projects are closely
related,
you must build all of the modules simultaneously from a master build.
While building all of the modules from source can work well and is handled by Maven inherently,
it can
lead to a number of problems:
• It relies on manual updates from developers, which can be error-prone. This will result in local
inconsistencies that can produce non-working builds
• There is no common baseline against which to measure progress
• Building can be slower as multiple dependencies must be rebuilt also
• Changes developed against outdated code can make integration more difficult
As you can see from these issues, building from source doesn't fit well with an environment that
promotes continuous integration. Instead, use binary snapshots that have been already built and
tested.
In Maven, this is achieved by regularly deploying snapshots to a shared repository, such as the
internal repository set up in section 7.3. Considering that example, you'll see that the repository
was
defined in proficio/trunk/pom.xml:
[...]
<distributionManagement>
<repository>
<id>internal</id>
<url>file://localhost/C:/mvnbook/repository/internal</url>
</repository>
[...]
</distributionManagement>
The -U argument in the prior command is required to force Maven to update all of the snapshots
in
the build. If it were omitted, by default, no update would be performed. This is because the
default
policy is to update snapshots daily – that is, to check for an update the first time that particular
dependency is used after midnight local time.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 25
JAVA Means DURGASOFT
We can also change the interval by changing the repository configuration. To see this, add the
following configuration to the repository configuration you defined above in
proficio/trunk/pom.xml:
[...]
<repository>
[...]
<snapshots>
<updatePolicy>interval:60</updatePolicy>
</snapshots>
</repository>
[...]
In this example, any snapshot dependencies will be checked once an hour to determine if there
are
updates in the remote repository. The settings that can be used for the update policy are never,
always, daily (the default), and interval:minutes.
Code Compile:
mvn test will always run the compile and test-compile phases first
Making a JAR file is straightforward and can be accomplished by executing the following
command:
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 26
JAVA Means DURGASOFT
create a basic Web site for your project, simply execute the following command:
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 27
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 28
JAVA Means DURGASOFT
To deploy to the file system you would use something like the following:
<project>
[...]
<distributionManagement>
<repository>
<id>proficio-repository</id>
<name>Proficio Repository</name>
<url>file://${basedir}/target/deploy</url>
</repository>
</distributionManagement>
[...]
</project>
To deploy to an SSH2 server you would use something like the following:
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 29
JAVA Means DURGASOFT
<project>
[...]
<distributionManagement>
<repository>
<id>proficio-repository</id>
<name>Proficio Repository</name>
<url>scp://sshserver.yourcompany.com/deploy</url>
</repository>
</distributionManagement>
[...]
</project>
To deploy to an SFTP server you would use something like the following:
<project>
[...]
<distributionManagement>
<repository>
<id>proficio-repository</id>
<name>Proficio Repository</name>
<url>sftp://ftpserver.yourcompany.com/deploy</url>
</repository>
</distributionManagement>
[...]
</project>
Deployment Automation:
Check-in the code from all project in progress into the SVN or source code repository and
tag it.
Download the complete source code from SVN.
Build the application.
Store the build output either WAR or EAR file to a common network location.
Get the file from network and deploy the file to the production site.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 30
JAVA Means DURGASOFT
Updated the documentation with date and updated version number of the application.
Problem Statement :
There are normally multiple people involved in above mentioned deployment process. One team
may handles check-in of code, other may handle build and so on. It is very likely that any step
may get missed out due to manual efforts involved and owing to multi-team environment. For
example, older build may not be replaced on network machine and deployment team deployed
the older build again.
Solution :
Automate the deployment process by combining
Maven, to build and release projects,
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>bus-core-api</groupId>
<artifactId>durga-soft-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<scm>
<url>http://www.svn.com</url>
<connection>scm:svn:http://localhost:8080/svn/jrepo/trunk/
Framework</connection>
<developerConnection>scm:svn:${username}/${password}@localhost:8080:
common_core_api:1101:code</developerConnection>
</scm>
<distributionManagement>
<repository>
<id>Core-API-Java-Release</id>
<name>Release repository</name>
<url>http://localhost:8081/nexus/content/repositories/
Core-Api-Release</url>
</repository>
</distributionManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.0-beta-9</version>
<configuration>
<useReleaseProfile>false</useReleaseProfile>
<goals>deploy</goals>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 31
JAVA Means DURGASOFT
<scmCommentPrefix>[durga-soft-api-release-checkin]-<
/scmCommentPrefix>
</configuration>
</plugin>
</plugins>
</build>
</project>
Element Description
SCM Configures the SVN location from where
Maven will check out the source code.
Repositories Location where built WAR/EAR/JAR or any
other artifact will be stored after code build is
successful.
Plugin maven-release-plugin is configured to
automate the deployment process.
mvn release:clean
It cleans the workspace in case the last release process was not successful.
mvn release:rollback
Rollback the changes done to workspace code and configuration in case the last release process
was not successful.
mvn release:prepare
Changes the version of the application and removes SNAPSHOT from the version to make
release
Increment the version number and append SNAPSHOT for future release
mvn release:perform
Checks out the code using the previously defined tag and run the Maven deploy goal to deploy
the war or built artifact to repository
Maven will start processing and will create the complete web based java application project
structure.
[INFO] --------------------------------------------------------------------
[INFO] Using following parameters for creating project
from Old (1.x) Archetype: maven-archetype-webapp:1.0
[INFO] --------------------------------------------------------------------
[INFO] Parameter: groupId, Value: com.companyname.automobile
[INFO] Parameter: packageName, Value: com.companyname.automobile
[INFO] Parameter: package, Value: com.companyname.automobile
[INFO] Parameter: artifactId, Value: trucks
[INFO] Parameter: basedir, Value: C:\MVN
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\MVN\trucks
[INFO] -------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] -------------------------------------------------------------------
[INFO] Total time: 16 seconds
[INFO] Finished at: Tue Jul 17 11:00:00 IST 2012
[INFO] Final Memory: 20M/89M
[INFO] -------------------------------------------------------------------
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 34
JAVA Means DURGASOFT
Maven uses a standard directory layout. Using above example, we can understand following key
concepts
POM.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.companyname.automobile</groupId>
<artifactId>DurgaWeb</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>trucks Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>DurgaWeb</finalName>
</build>
</project>
C:\ >Development> DuregaWeb> src > main > webapp > you will see index.jsp.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 35
JAVA Means DURGASOFT
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
Let's open command console, go the C:\Devlopment\DurgaWeb\ directory and execute the
following mvn command.
Now copy the DurgaWeb.war created in C:\ > Development >DurgaWeb > target > folder to your
webserver webapp directory and restart the webserver.
Eclipse provides an excellent plugin m2eclipse which seamlessly integrates Maven and Eclipse
together.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 37
JAVA Means DURGASOFT
You can view the output of Maven commands inside the Eclipse using its own console.
It does the dependency management for Eclipse build path based on Maven's pom.xml.
It resolves Maven dependencies from the Eclipse workspace without installing to local Maven
repository (requires dependency project be in same workspace).
It automatic downloads required dependencies and sources from the remote Maven
repositories.
Eclipse URL
Eclipse 3.5 (Gallileo) http://www.sonatype.com/books/
m2eclipse-
book/reference/ch02s03.html
Eclipse 3.6 (Helios) http://www.sonatype.com/books/
m2eclipse-book/reference/install-
sect-marketplace.html
Open Eclipse.
Select Project location, where a project was created using Maven. We've create a Java
Project consumerBanking.See Maven Creating Project to see how to create a project using
Maven.
Click Finish Button.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 39
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 40
JAVA Means DURGASOFT
Now, have a look at consumerBanking project properties. You can see that Eclipse has added Maven
dependencies to java build path.
Now, Its time to build this project using maven capability of eclipse.
Maven will start building the project. You can see the output in Eclipse Console.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 41
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 42
JAVA Means DURGASOFT
Now, right click on App.java. Select Run As option. Select As Java Application. You will see the result
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 43
JAVA Means DURGASOFT
Maven Programs
1) Struts Application
2) Hibernate Application
3) Spring using JDBC
4) Sample Web Application.
Struts Application
Steps to Struts Application using Maven
Generate a simple webapp with archetype:generate:
C:\Development>mvn archetype:generate -
DarchetypeArtifactId=maven-archetype-webapp -DgroupId=maven-
tutorial -DartifactId=struts1app
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 44
JAVA Means DURGASOFT
C:\Development>
struts1app
struts1app/pom.xml
struts1app/src
struts1app/src/main
struts1app/src/main/resources
struts1app/src/main/webapp
struts1app/src/main/webapp/index.jsp
struts1app/src/main/webapp/WEB-INF
struts1app/src/main/webapp/WEB-INF/web.xml
Simple POM:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 45
JAVA Means DURGASOFT
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>maven-tutorial</groupId>
<artifactId>struts1app</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>struts1app Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>struts1app</finalName>
</build>
</project>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 46
JAVA Means DURGASOFT
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<repositories>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>
</profile>
</profiles>
</settings>
Add Java EE and Struts dependencies in pom.xml. Note that the Java EE
dependency has scope provided, meaning that the web app container
provides the jars, therefore we don't need to bundle them with our war
fie.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>maven-tutorial</groupId>
<artifactId>struts1app</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>struts1app Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>6.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 47
JAVA Means DURGASOFT
<dependency>
<groupId>struts</groupId>
<artifactId>struts</artifactId>
<version>1.2.9</version>
</dependency>
</dependencies>
<build>
<finalName>struts1app</finalName>
</build>
</project>
Create a directory named java under main, create the Struts form and
action classes:
src/main/java
src/main/java/com
src/main/java/com/dss
src/main/java/com/dss/HelloAction.java
src/main/java/com/dss/HelloForm.java
HelloForm.java
package com.dss;
import org.apache.struts.action.ActionForm;
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 48
JAVA Means DURGASOFT
HelloAction.java
package com.dss;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
Create a directory named jsp under webapp, and create 2 jsp files:
index.jsp:
<html>
<body>
<html:form action="/hello" method="post">
Enter Name: <html:text property="name"/>
<br/>
<input type="submit" name="submit" value="Go"/>
</html:form>
</body>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 49
JAVA Means DURGASOFT
</html>
hello.jsp:
<html>
<body>
<h2>Hello, <bean:write name="name"/>!</h2>
</body>
</html>
<html>
<head>
<meta http-equiv="refresh" content="0;URL=index.do">
</head>
<body>
</body>
</html>
<struts-config>
<global-forwards>
<forward name="index" path="/jsp/index.jsp"/>
</global-forwards>
<form-beans>
<form-bean name="helloForm" type="com.dss.HelloForm" />
</form-beans>
<action-mappings>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 50
JAVA Means DURGASOFT
<action
path="/index"
name="helloForm"
type="org.apache.struts.actions.ForwardAction"
parameter="/jsp/index.jsp"
validate="false">
</action>
<action path="/hello"
name="helloForm"
scope="request"
type="com.dss.HelloAction"
validate="false">
<forward name="hello" path="/jsp/hello.jsp" />
</action>
</action-mappings>
</struts-config>
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
struts1app
struts1app/pom.xml
struts1app/src
struts1app/src/main
struts1app/src/main/java
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 51
JAVA Means DURGASOFT
struts1app/src/main/java/com
struts1app/src/main/java/com/dss
struts1app/src/main/java/com/dss/HelloAction.java
struts1app/src/main/java/com/dss/HelloForm.java
struts1app/src/main/resources
struts1app/src/main/webapp
struts1app/src/main/webapp/index.jsp
struts1app/src/main/webapp/jsp
struts1app/src/main/webapp/jsp/hello.jsp
struts1app/src/main/webapp/jsp/index.jsp
struts1app/src/main/webapp/WEB-INF
struts1app/src/main/webapp/WEB-INF/struts-config.xml
struts1app/src/main/webapp/WEB-INF/web.xml
Maven will generates struts1app.war and place it in target folder. Take the war
file and deploy it in server.
==================================================
Hibernate with Maven Application
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 52
JAVA Means DURGASOFT
To convert the generated Maven based project to Eclipse project, and import it
mvn eclipse:eclipse
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dss.common</groupId>
<artifactId>HibernateExample</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<name>HibernateExample</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>JBoss repository</id>
<url>http://repository.jboss.org/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<version>10.2.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.3.Final</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.1.GA</version>
</dependency>
</dependencies>
</project>
Create a Hibernate XML mapping file and Model class for table “DBUSER“.
File : DBUser.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 54
JAVA Means DURGASOFT
<hibernate-mapping>
<class name="com.dss.user.DBUser" table="DBUSER">
<id name="userId" type="int">
<column name="USER_ID" precision="5" scale="0" />
<generator class="assigned" />
</id>
<property name="username" type="string">
<column name="USERNAME" length="20" not-null="true" />
</property>
<property name="createdBy" type="string">
<column name="CREATED_BY" length="20" not-null="true" />
</property>
<property name="createdDate" type="date">
<column name="CREATED_DATE" length="7" not-null="true" />
</property>
</class>
</hibernate-mapping>
File : DBUser.java
package com.dss.user;
import java.util.Date;
public DBUser() {
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 55
JAVA Means DURGASOFT
Create a Hibernate configuration file “hibernate.cfg.xml” and put it under the root of resources folder,
“src/main/resources/hibernate.cfg.xml“, and fill in your Oracle database details. And map to above
Hibernate mapping file – “DBUser.hbm.xml“.
File : hibernate.cfg.xml
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 56
JAVA Means DURGASOFT
7. Hibernate Utility
Create a classic “HibernateUtil.java” class to take care of Hibernate session management. And put
under “src/main/java/com/dss/util/HibernateUtil.java”
File : HibernateUtil.java
package com.dss.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
Hibernate Coding
Update “App.java”, to code Hibernate to save a dummy user record into a table
“DBUSER”.
File : App.java
package com.dss;
import java.util.Date;
import org.hibernate.Session;
import com.dss.util.HibernateUtil;
import com.dss.user.DBUser;
session.beginTransaction();
DBUser user = new DBUser();
user.setUserId(100);
user.setUsername("superman");
user.setCreatedBy("system");
user.setCreatedDate(new Date());
session.save(user);
session.getTransaction().commit();
}
}
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 58
JAVA Means DURGASOFT
);
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dss.common</groupId>
<artifactId>SpringJDBCExample</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringJDBCExample</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 59
JAVA Means DURGASOFT
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0</version>
</dependency>
</dependencies>
</project>
Customer model
package com.dss.customer.model;
import java.sql.Timestamp;
package com.mkyong.customer.dao;
import com.mkyong.customer.model.Customer;
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 60
JAVA Means DURGASOFT
Customer Dao implementation, JdbcCustomerDAO.java use JDBC to issue a simple insert and select
statement.
package com.dss.customer.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.dss.customer.dao.CustomerDAO;
import com.dss.customer.model.Customer;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, customer.getCustId());
ps.setString(2, customer.getName());
ps.setInt(3, customer.getAge());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, custId);
Customer customer = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customer = new Customer(
rs.getInt("CUST_ID"),
rs.getString("NAME"),
rs.getInt("Age")
);
}
rs.close();
ps.close();
return customer;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
}
Create the Spring bean configuration file for customerDAO and datasource.
Crate File Spring-Customer.xml under src/main/resources/customer/
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 62
JAVA Means DURGASOFT
</bean>
</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
</beans>
Run App.java
package com.dss.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.dss.customer.dao.CustomerDAO;
import com.dss.customer.model.Customer;
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 63
JAVA Means DURGASOFT
}
}
C:\Development>
ServletMavenDSS
ServletMavenDSS /pom.xml
ServletMavenDSS/src
ServletMavenDSS/src/main
ServletMavenDSS/src/main/resources
ServletMavenDSS/src/main/webapp
ServletMavenDSS/src/main/webapp/index.jsp
ServletMavenDSS/src/main/webapp/WEB-INF
ServletMavenDSS/src/main/webapp/WEB-INF/web.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.dsstest</groupId>
<artifactId>ServletMavenDSS</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>mywebtest Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>ServletMavenDSS</finalName>
</build>
</project>
Type Command:
C:\Development> mvn install
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 64
JAVA Means DURGASOFT
Maven will compile all the source files place all the class files in target
folder, Unittesting will be done, and generate war file place in target folder.
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 65
JAVA Means DURGASOFT
nd
DURGASOFT, # 202,2 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 040 – 64 51 27 86, 80 96 96 96
96, 9246212143 | www.durgasoft.com Page 66