Tag Archives: Java - Page 2

Spring, Hibernate, Maven, and Struts2 integration tutorial – part 3

This is part 3 of the Java Technologies Integration tutorial

Sping Beans

Having user entity create it is finally the time to write some code! We are going to create two Spring Beans: Bussiness Object (BO) to providing interface for bussiness operations and Data Access Object (DAO) to communicate with database using entity User. To do so, we create two interfaces (UserBo and UserDao) and their implementations (UserBoImpl and UserDaoImpl) in package com.frogdroid.integration.user. The content of the files is listed below.

UserBo.java

package com.frogdroid.integration.user;
 
import java.util.List;
 
import com.frogdroid.integration.user.entity.User;
 
public interface UserBo {
 
    void add(User user);
 
    void update(User user);
 
    void delete(User user);
 
    List findAll();
 
    List findById(int id);
 
    List findByUsername(String username);
}

UserBoImpl.java

 
package com.frogdroid.integration.user;
 
import java.util.List;
 
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
 
import com.frogdroid.integration.user.entity.User;
 
@Transactional
public class UserBoImpl implements UserBo {
 
    private static final Logger LOGGER = Logger.getLogger(UserBoImpl.class.getName());
 
    @Autowired
    private UserDao userDao;
 
    public UserDao getUserDao() {
        return userDao;
    }
 
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
 
    public void add(User user) {
        if (user == null) {
            return;
        }
        LOGGER.debug("Adding the following user: " + user.getUsername() + ", " + user.getPassword());
        userDao.add(user);
    }
 
    public void delete(User user) {
        if (user == null) {
            return;
        }
        LOGGER.debug("Deleteting the following user: " + user.getId() + ", " + user.getUsername() + ", " + user.getPassword());
        userDao.delete(user);
    }
 
    public List findAll() {
        LOGGER.debug("Getting all users");
        return userDao.findAll();
    }
 
    public List findById(int id) {
        return userDao.findById(id);
    }
 
    public List findByUsername(String username) {
        return userDao.findByUsername(username);
    }
 
    public void update(User user) {
        if (user == null) {
            return;
        }
        userDao.update(user);
    }
}

UserDao.java

package com.frogdroid.integration.user;
 
import java.util.List;
 
import com.frogdroid.integration.user.entity.User;
 
public interface UserDao {
 
    void add(User user);
 
    void update(User user);
 
    void delete(User user);
 
    List findAll();
 
    List findById(int id);
 
    List findByUsername(String username);
}

UserDaoImpl.java

package com.frogdroid.integration.user;
 
import java.util.List;
 
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 
import com.frogdroid.integration.user.entity.User;
 
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
 
    public void add(User user) {
        getHibernateTemplate().save(user);
    }
 
    public void delete(User user) {
        getHibernateTemplate().delete(user);
    }
 
    public List findAll() {
        return getHibernateTemplate().find("from User");
    }
 
    public List findById(int id) {
        return getHibernateTemplate().find("from User where id=?", id);
    }
 
    public List findByUsername(String username) {
        return getHibernateTemplate().find("from User where username=?", username);
    }
 
    public void update(User user) {
        getHibernateTemplate().update(user);
    }
}

Following that we create appropriate bean definitions and put them in src/main/resources/resources/spring/UserBean.xml file.

UserBean.xml

 
<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="userBo" class="com.frogdroid.integration.user.UserBoImpl">
		<property name="userDao" ref="userDao" />
	</bean>
 
	<bean id="userDao" class="com.frogdroid.integration.user.UserDaoImpl">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
 
</beans>

In addition we include UserBean.xml file in src/main/webapp/WEB-INF/applicationContext.xml file as follows:

<!-- Beans Declaration -->
<import resource="classes/resources/spring/UserBean.xml" />

Structure of the project after changes is presented in Figure 10.


Figure 10: Project with BOs, DAOs and their configuration.

Integration with Struts2

To use Struts2 in our project we have to add filter to web.xml file. The filter will be mapped, so each request to *.action and struts/* will be executed through StrutsPrepareAndExecuteFilter. The part to be added to web-app section in web.xml is presented below.

<filter>
	<filter-name>struts2</filter-name>
	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
 
<filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>*.action</url-pattern>
</filter-mapping>
 
<filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/struts/*</url-pattern>
</filter-mapping>

Following that we have to create UserAction class that runs appropriate actions and return input to StrutsPrepareAndExecuteFilter. The class is put in src/main/java/com/frogdroid/integration/user/action/UserAction.java and its content is listed below.

UserAction.java

package com.frogdroid.integration.user.action;
 
import java.util.List;
 
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
 
import com.frogdroid.integration.user.UserBo;
import com.frogdroid.integration.user.entity.User;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.Preparable;
 
public class UserAction implements Preparable {
 
    private static final Logger LOGGER = Logger.getLogger(UserAction.class.getName());
 
    private List users;
 
    private Integer id;
    private String username;
    private String password;
 
    @Autowired
    private UserBo userBo;
 
    public UserBo getUserBo() {
        return userBo;
    }
 
    public void setUserBo(UserBo userBo) {
        this.userBo = userBo;
    }
 
    public List getUsers() {
        return users;
    }
 
    public void setUsers(List users) {
        this.users = users;
    }
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getUsername() {
        return username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
    public String getPassword() {
        return password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public String listAll() {
        if (userBo == null) {
            return Action.ERROR;
        }
        LOGGER.debug("Get all users");
        users = userBo.findAll();
        LOGGER.debug("Users number = " + users.size());
        return Action.SUCCESS;
    }
 
    public String delete() {
        if (userBo == null) {
            return Action.ERROR;
        }
 
        User user = getUser(id);
        if (user == null) {
            return Action.ERROR;
        }
 
        LOGGER.debug("Delete user " + user.getUsername() + " with id " + user.getId());
        userBo.delete(user);
        return Action.SUCCESS;
    }
 
    public String add() {
        if (userBo == null) {
            return Action.ERROR;
        }
 
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        LOGGER.debug("Add user: " + user.getUsername());
        userBo.add(user);
        return Action.SUCCESS;
    }
 
    public String execute() {
        return Action.SUCCESS;
    }
 
    public void prepare() throws Exception {
 
    }
 
    private User getUser(Integer id) {
        LOGGER.debug("Get user with id = " + id);
        if (id != null) {
            List users = userBo.findById(id);
            LOGGER.debug("Number of users with id = " + id + ": " + users.size());
            if (users.size() == 1) {
                return (User) users.get(0);
            }
        }
        return null;
    }
}

We add the following action bean definition to UserBean.xml file, so it can be used in struts action file.

<bean id="userAction" class="com.frogdroid.integration.user.action.UserAction">
	<property name="userBo" ref="userBo" />
</bean>

Following that we have to create file with struts actions. The file should be placed in WEB-INF/classes/struts.xml in final war structure, which indicates that it should be created in src/main/resources/struts.xml. If you use different location struts actions will not be mapped. The file mapps actions invoked by the user to appropriate java classes/beans and its content is presented below. Depending on action appropriate methods (listAll, delete, add) from UserAction class are invoked. Our application has the functionality to list, add, and delete users from database.

struts.xml

 
<!DOCTYPE struts PUBLIC
     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
     "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
 
	<constant name="struts.devMode" value="true" />
 
	<package name="default" extends="struts-default">
 
		<action name="listAllUsers" method="listAll" class="userAction">
			<result name="success">WEB-INF/content/user/list.jsp</result>
		</action>
 
		<action name="deleteUser" method="delete" class="userAction">
			<result type="redirect">listAllUsers.action</result>
		</action>
 
		<action name="addUserForm" class="userAction">
			<result>WEB-INF/content/user/addForm.jsp</result>
		</action>
 
		<action name="addUser" method="add" class="userAction">
			<result type="redirect">listAllUsers.action</result>
		</action>
 
	</package>
</struts>

To show add user form we have to create WEB-INF/content/user/addForm.jsp file and to list all users we have to create WEB-INF/content/user/list.jsp. The content of the files is presented below.

addForm.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
 
<html>
<head>
<title>Add User</title>
</head>
<body>
 
<p>Add User</p>
 
<s:form name="addForm" method="post" action="addUser.action">
 
	<s:textfield name="username" label="User" />
	<s:password name="password" label="Password" />
 
	<s:submit type="button" name="Add" />
 
</s:form>
 
</body>
</html>

Make sure that the names of the fields correspond to properties in your UserAction class.

list.jsp

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
 
<html>
<head>
<title>User List</title>
<sx:head debug="true" cache="false" compressed="false" />
</head>
<body>
 
<p>User List</p>
<div><s:url id="addUser" value="addUserForm.action">
</s:url><s:a href="%{addUser}">Add</s:a></div>
<s:if test="users.size > 0">
	<table id="users">
		<s:iterator value="users">
			<tr>
				<td><s:property value="username" /></td>
				<td><s:property value="password" /></td>
				<td><s:url id="deleteUser" value="deleteUser.action">
					<s:param name="id" value="id" />
				</s:url> <s:a href="%{deleteUser}">Delete</s:a></td>
			</tr>
		</s:iterator>
	</table>
</s:if>
 
</body>
</html>

Make sure that the names of the properties correspond to properties in your User entity. In addition, iterator uses property (‘users’) that should be defined in UserAction class.

The structure of the project after changes is presented in Figure 11.


Figure 11: Project structure after integration with Struts2″.

Final struture

Before showing final project structure let’s tidy a little bit up. Remove:

  • Remove class: App.java
  • Remove class: AppTest.java
  • Change Default output folder (Java build path -> Source) to IntegrationProject/target/classes
  • Remove folder: build

Having all that done the final structure of the project should look as presented in Figure 12.


Figure 12: Final project structure.

Test that all is OK so far:

mvn clean
mvn compile
mvn war:war

Part 4 of the tutorial can be found at Java Technologies Integration tutorial – part 4.

Spring, Hibernate, Maven, and Struts2 integration tutorial – part 2

This is part 2 of the Java Technologies Integration tutorial

Integration with Spring and Hibernate

In order to integrate the project with Spring and Hibernate a number of the files presented in Figure 5 have to be created. The content of the files is presented in the following part of this section.


Figure 5: Files needed for integration with Hibernate and Spring.

database.properties

This file includes information used to connect to database. We use MySQL database to store our data. Make sure that jdbc.url, jdbc.username, and jdbc.password are updated with your settings.

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/IntegrationProject
jdbc.username=integrationProjectUser
jdbc.password=integrationProjectPassword

log4j.properties

This file includes information used to log the data. For more information refer to log4j. Again, replace bold values with the correct settings.

### direct log messages to stdout ###
log4j.rootLogger=ERROR, console, file

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.layout=org.apache.log4j.SimpleLayout

# AdminFileAppender - used to log messages in the admin.log file.
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=path_to_your_log_directory/IntegrationProject.log
log4j.appender.file.layout=org.apache.log4j.SimpleLayout

log4j.logger.com.frogdroid=DEBUG, console, file

DataSource.xml

Spring Bean defined to connect to database.

<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 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>WEB-INF/classes/resources/database/database.properties</value>
		</property>
	</bean>
 
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>
 
</beans>

Hibernate.xml

Spring Bean defined to create session factory for hibernate.

<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">
 
	<!-- Hibernate session factory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
 
		<property name="dataSource">
			<ref bean="dataSource" />
		</property>
 
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
 
		<property name="mappingResources">
			<list />
		</property>
 
	</bean>
</beans>

applicationContext.xml

This file is used by Spring to create appropriate Spring Beans. For convenience it includes imports of appropriate files with Spring Beans. applicationContext.xml is default name and can be changed in web.xml file.

<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">
 
	<!-- Database Configuration -->
	<import resource="classes/resources/spring/config/DataSource.xml" />
	<import resource="classes/resources/spring/config/Hibernate.xml" />
 
</beans>

Updates to web.xml

In order to enable the integration the following changes should be done to web.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
	<display-name>IntegrationProject</display-name>
 
	<!-- Spring beans -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext.xml </param-value>
	</context-param>
 
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/classes/resources/logs/log4j.properties</param-value>
	</context-param>
 
	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
 
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
 
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
 
</web-app>

Entities

To communicate with database using Hibernate we have to create entities, which are layer between database and business interface of our application. The most convenient way to do that in Eclipse is to add MySQL database to data sources and create entity directly from the table. In order to do so, select:

File -> New -> Connection Profiles -> Connection Profile
Select: MySQL
Enter data as shown in Figure 6.


Figure 6: Configuration of MySQL connection in Eclipse.

After clicking connect on the database in Data Source Explorer you should be able to see the following view (Figure 7). Note, that our database ‘integrationproject’ includes table ‘users’ which consists of 3 fields: ‘id’, ‘username’, and ‘password’.


Figure 7: View on database in Eclipse.

Entity creation

To create entity from database table create JPA project:

File -> New -> JPA -> JPA Project

Enter:
Project name: IntegrationProjectJPA
Target runtime: [Tomcat server configured before]
Configuration: Utility JPA Project with Java 5.0

Following that select:
File -> New -> JPA -> Entities From Tables

Configure custom entities generation as shown in Figure 8.


Figure 8: Generation of custom entities.

Copy User.java file which was created to IntegrateProject under the path src/main/java/com/frogdroid/integration/user/entity/ and fix package name. Remove serialVersionUID variable. The content of User.java file is listed below.

 
package com.frogdroid.integration.user.entity;
 
import java.io.Serializable;
import javax.persistence.*;
 
/**
 * The persistent class for the users database table.
 * 
 */
@Entity
@Table(name = "users")
public class User implements Serializable {
 
    @Id
    private int id;
 
    private String password;
 
    private String username;
 
    public User() {
    }
 
    public int getId() {
        return this.id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getPassword() {
        return this.password;
    }
 
    public void setPassword(String password) {
        this.password = password;
    }
 
    public String getUsername() {
        return this.username;
    }
 
    public void setUsername(String username) {
        this.username = username;
    }
 
}

XML mapping file creation

We will also need mapping file – it is required by Hibernate factory bean (Hibernate.xml). To create the mapping file select:

File -> New -> Hibernate -> Hibernate XML Mapping File (hbm.xml)

Select: Add Class… and enter: User
Select: User – com.frogdroid.integration.user.entity – IntegrationProject/src/main/java

The file User.hbm.xml will be generated. Copy it to src/main/resources/resources/hibernate/. Change ‘table=”USER”‘ to ‘table=”USERS”‘. If present remove serialVersionUID property. The content of the file is presented below.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
    <class name="com.frogdroid.integration.user.entity.User" table="USERS">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
        <property name="username" type="java.lang.String">
            <column name="USERNAME" />
        </property>
    </class>
</hibernate-mapping>

Add mapping file to Hibernate configuration file (src/main/resources/resources/spring/config/Hibernate.xml) as follows:

<property name="mappingResources">
	<list>
		<value>resources/hibernate/User.hbm.xml</value>
	</list>
</property>

Structure of the project after changes is presented in Figure 9.


Figure 9: Project with entity.

Test that everything is working OK so far, run from the directory with pom.xml:

mvn clean
mvn compile
mvn war:war

Part 3 of the tutorial can be found at Java Technologies Integration tutorial – part 3.

Updates to the Hibernate configuration of the project can be found in part 5 of the tutorial, which can be found here Java Technologies Integration tutorial – part 5 – Hibernate update.

Spring, Hibernate, Maven, and Struts2 integration tutorial – part 1

Introduction

The purpose of this tutorial is to demonstrate the technical solution for integration of 4 leading frameworks:

Such a combination allow the development of you web applications with maximal of flexibility and minimal effort. In addition, the integration with SVN will be also demonstrated to enable the efficient development.

Prerequisites

Before we start you need the following tools:

Setup

Java

Remember to set the JAVA_HOME environment variable to point to the base path of the JDK.

Tomcat

To install Tomcat follow the instructions in installation guide. Remember to set the CATALINA_HOME environment variable to point to the base path of the Tomcat.

Alternative solution is to use Tomcat servers run in Eclipse. To configure it select:

File -> New -> Server -> Server
Select: Apache -> Tomcat 6.0

Choose Tomcat installation directory and click ‘Download and Install’

Tomcat should be downloaded to the directory you chose and server should appear in server list (Servers tab).

Maven

Download Maven from http://maven.apache.org/download.html and unpack it to local directory. Set environment variable M2_HOME to point to directory with Maven.

MySQL and Database

Install and configure MySQL. Create a database named ‘IntegrationProject’ and run the script below to create the “Users” table.

CREATE TABLE `USERS` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(50) NOT NULL,
  `password` VARCHAR(50) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `username` (`username`)
) ENGINE=MyISAM ;

Development

Having all that set up we can finally start the development! First we have to create Maven project.

Maven project

To create the default Maven project we execute:

mvn archetype:generate

Maven downloads number of packages and following that asks about the archetype. Select default one (maven-archetype-quickstart) and define the following values:

Define value for groupId: com.frogdroid.integration
Define value for artifactId: IntegrationProject
Define value for version: 1.0
Define value for package: com.frogdroid.integration

The project should be created!

Eclipse Project

It is possible to tranform Maven project to Eclipse project using command:

mvn eclipse:eclipse

However, for convenience, our approach is to create Dynamic Web Project in Eclipse and integrate Maven project with it. Such approach allows to use Tomcat server integrated with Eclipse. To create Dynamic Web Project we select:

File -> New -> Web -> Dynamic Web Project

Enter:
Project name: IntegrationProject
Target runtime: [Tomcat server configured before] (or leave empty if you decided not to use Tomcat with Eclipse)

Copy the content of the Maven project into you Ecplise project and refresh it. You should see the structure presented in Figure 1.


Figure 1: Project structure after coping Maven Project into Ecplise project.

Fix the build path as in Figure 2.


Figure 2: Fix build path.

There are still some references to external libraries missing but we will deal with that later.

Configure project dependencies and Maven plugins

Maven is framework that deals with dependencies in our project. The convenient way to find the dependencies to be placed in pom.xml file is to use the Maven repository. The dependencies can be copied directly to pom.xml file. We will use following libraries:

  • junit
  • spring
  • hibernate
  • log4j
  • struts2-spring-plugin
  • struts2-dojo-plugin
  • mysql-connector-java
  • persistence-api

If the packages depend on different ones they will be downloaded automatically.
It also uses a number of different plugins to make Java application development more convenient.
In our project we use two plugins:

  • maven-compiler-plugin to configure java version that should be used to compile the sources
  • maven-war-plugin to build war file to be deployed on Tomcat server

pom.xml

The complete pom.xml file is presented below.

<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.frogdroid.integration</groupId>
	<artifactId>IntegrationProject</artifactId>
	<version>1.0</version>
	<packaging>jar</packaging>
 
	<name>IntegrationProject</name>
	<url>http://maven.apache.org</url>
 
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
 
	<dependencies>
 
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.1</version>
		</dependency>
 
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring</artifactId>
			<version>2.5.6</version>
		</dependency>
 
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate</artifactId>
			<version>3.2.7.ga</version>
		</dependency>
 
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>
 
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-spring-plugin</artifactId>
			<version>2.1.8</version>
		</dependency>
 
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-dojo-plugin</artifactId>
			<version>2.2.1</version>
		</dependency>
 
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.13</version>
		</dependency>
 
		<dependency>
			<groupId>javax.persistence</groupId>
			<artifactId>persistence-api</artifactId>
			<version>1.0</version>
		</dependency>
 
	</dependencies>
 
	<build>
		<plugins>
 
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.5</source>
					<target>1.5</target>
				</configuration>
			</plugin>
 
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<addClasspath>true</addClasspath>
							<classpathPrefix>lib/</classpathPrefix>
						</manifest>
					</archive>
				</configuration>
			</plugin>
 
		</plugins>
	</build>
</project>

Test dependencies

To download all the dependencies to local repository and test if project compiles execute:

mvn compile

Missing artifacts

It might happen that some of the artifacts are missing in the Maven repository, .e.g, javax.transaction:jta:jar:1.0.1B. In that case we can install missing artifact in the local repository manually. To do that download the missing artifact (jar file) and follow the instructions on screen. In case of javax.transaction:jta:jar:1.0.1B it can be downloaded from http://www.oracle.com/technetwork/java/javaee/tech/jta-138684.html (change zip extension to jar) and installed using the following command:

mvn install:install-file -DgroupId=javax.transaction -DartifactId=jta -Dversion=1.0.1B -Dpackaging=jar -Dfile=jta-1_0_1B.jar

Web application development

Convinient way to develop Web applications with Maven is to use maven-war-plugin. This plugin enforces special project structure. The web sources should be placed in src/main/webapp folder therefore we have to create src/main/webapp folder in our project. Copy whole directory WebContent/WEB-INF to src/main/webapp/. In addition we create src/main/resources folder. The content of this folder is copied directly in WEB-INF/classes after creation of war file. The file structure is presented in Figure 3.


Figure 3: File structure of web project.

War file creation

Having all that done we finally can create war file. To do so, execute the following command:

mvn war:war

The file will be created in target directory. That is also the directory where compiled code is put. Compiled java classes can be found in target/classes. Content of war file can be found in our case in target/IntegrationProject-1.0 and the war file itself in target/IntegrationProject-1.0.war. Configuration of maven-war-plugin indicates that directories that project depends on are included and placed in lib directory, so full path to them is target/IntegrationProject-1.0/WEB-INF/lib.

<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>

The content of target directory after build of war file is presented in Figure 4.


Figure 4: The content of target directory.

Adding dependencies to Ecplise build path

Having all the libraries needed for the development of the project we can finally add them to Eclipse build path (add external jars). Add jar files located in target/IntegrationProject-1.0/WEB-INF/lib to Java build path. Remember to update build path after adding/removing dependencies to/from pom.xml file.

Part 2 of the tutorial can be found at Java Technologies Integration tutorial – part 2.

How to display all MySQL queries your application generates.

Sometimes it’s a good idea to intercept the SQL queries exactly as they are generated by your Java application. One way to do it (in MySQL) is to enable general_log. Another really handy option is to use MySQL JDBC driver option: autoGenerateTestcaseScript. It will dump all the queries to standard error, as they are being sent to the database.

com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
ds.setAutoGenerateTestcaseScript(true);
ds.setURL("jdbc:mysql://host:port/dbname");
Connection con = ds.getConnection("user", "password");
//...

This will give you on your stderr output like this:


/* conn id 384 */ SELECT * FROM user WHERE id = 2;
/* conn id 384 */ SELECT * FROM user WHERE id = 1;