Spring MVC with Annotations , JPA , Derby , Fileupload, SWFUpload CRUD Example

This is my attempt to create a clear tutorial on Spring MVC CRUD using JPA and Derby and a sample FileUpload with SWFUpload

I have tried to use standard file structure and naming patterns so that it will be useful in proceeding further on this base

First of all To create any Spring Application we need to configure DispatcherServlet in Servlet in Web.xml of Application so that all SpringMVC related requests goto to that servlet

Here is sample code snippet of web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Use this definition if using a Java EE 6 container This also stops Eclipse
	from complaining that 3.0 is not a valid version <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
	http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">

	<!-- The definition of the Root Spring Container shared by all Servlets
		and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>

	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/app/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>

</web-app>

Now that we have defined DispatcherServlet in Web.xml, let me define each file and its usage so that you can download and change what ever us required for you

WEB-INF
│ web.xml : Servlet Configuration Defined Here

├───spring
│ │ db.xml : DB related Beans Configured Here
│ │ root-context.xml
│ │
│ └───app
│ controllers.xml : Contrller Configuration defined here. We are using annotation so we just tell spring that use annotation handler to indefiy files
I also added a multipart resolver to handle multipart request here.
│ servlet-context.xml: Core Spring MVC Configuration file which is root file where spring MVC reads. I defined resources/view resolver/validator/and controller here

└───views
│ edit.jsp : Sample page to show edit functionaly
│ home.jsp : Welcome Page
│ list.jsp : List records page
│ upload.jsp : Simple Upload Functionality using SWFUpload is defined here

└───forms
success.jsp
upload.jsp

src/main/
│ │
│ ├───resources
│ │ │ db.properties : DB connectivity Properties to connect
│ │ │ log4j.xml : Logiing related xml
│ │ │
│ │ └───META-INF
│ │ persistence.xml : JPA Configuration file
│ │

Here is code of my File Upload Controller

/**
 *
 */
package com.linkwithweb.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.linkwithweb.spring.model.UploadBean;

/**
 * @author Ashwin Kumar
 *
 */

@Controller
@RequestMapping("/upload/")
public class UploadController {

	public UploadController() {
	}

	@RequestMapping(method = RequestMethod.GET)
	public String getUploadForm(Model model) {
		model.addAttribute("uploadbean", new UploadBean());
		return "forms/upload";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String Uploadcreate(UploadBean uploadbean, BindingResult result) {
		System.out.println("started uploading");
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error in uploading: " + error.getCode()
						+ " - " + error.getDefaultMessage());
			}
			return "forms/upload";
		}

		// Some type of file processing...
		System.err.println("-------------------------------------------");

		System.err.println("Test uploading file: "
				+ uploadbean.getFiledata().getOriginalFilename());
		System.err.println("-------------------------------------------");		return "forms/success";
	}
}

Note: You have define Multipart resolver bean of commons file upload inorder to parse file upload requests

	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="100000" />
	</bean>

Code can be found at following SVN location
https://linkwithweb.googlecode.com/svn/trunk/SpringTutorials/SpringApp

Once downloaded run ” mvn jetty:run” to test the application at follwoing URL

http://localhost:8080/SpringApp/

http://localhost:8080/SpringApp/spring/upload/

Advertisements

Derby Tutorial Mavenized with Unit Test and Loading Data from Excel

Many applications requirement where they want to store some data at runtime and able to query using SQL. We wouldn’t like to install a full fledged database in such scenarios.
Apache has come up with a light weight database named Derby which suits the purpose. I would like to publish usage of Apache derby in java and how to use it. This tutorial is targetted to any one who understands java

This example rotates around a simple table person

ID NAME FIRST_NAME BIRTH_DATE
1 Jim Hammond 12/12/1974
2 Robert Grass 2/6/1968
3 John Kazyncksy 5/3/2000

This data is loaded by program from an excel file to Derby Database

As i’m using maven i’ll first define my pom here

4.0.0
com.ashwin.test.derby
derby
Derby Example
1.0.0

org.apache.maven.plugins
maven-compiler-plugin

1.5
1.5

org.apache.maven.plugins
maven-surefire-plugin

<!--

Be sure that JAVA_HOME points to a JDK6 installation
${env.JAVA_HOME}/db/lib/derby.jar

-->

org.apache.maven.plugins
maven-source-plugin

attach-sources
verify

jar

org.dbunit
dbunit
2.2.2
test

org.apache.derby
derby
10.6.2.1

Now as we defined our POM. Now lets try to load some data into derby. As derby is inmemory database we dont need to start any db server before hand. I created a base class which return DB Connection url and driver class

package com.linkwithweb.test.derby.dao;

import org.dbunit.JdbcBasedDBTestCase;
import org.dbunit.dataset.IDataSet;

/**
* An abstract Jdbc test case that factorizes the common methods.
*
* @author Ashwin
* @since 16th Nov 2010
*/
public abstract class AbstractDaoTest extends JdbcBasedDBTestCase {

/**
* @see org.dbunit.JdbcBasedDBTestCase#getConnectionUrl()
*/
@Override
protected String getConnectionUrl() {
return "jdbc:derby:myDB;create=true";
}

/**
* @see org.dbunit.JdbcBasedDBTestCase#getDriverClass()
*/
@Override
protected String getDriverClass() {
return "org.apache.derby.jdbc.EmbeddedDriver";
}

/**
* @see org.dbunit.DatabaseTestCase#getDataSet()
*/
@Override
protected IDataSet getDataSet() throws Exception {
return getConnection().createDataSet();
}
}

Now let me create a class Table Creator which loads Data into the Database

package com.linkwithweb.test.derby.dao;

import java.sql.Statement;

/**
* Run once in order to create the tables.
*
* @author Ashwin
* @since 16th Nov 2010
*/
public class TableCreator extends AbstractDaoTest {

/**
* Initializes the DB. Must be run once and only once to create structure.
*
* @throws Exception
*/
public void initialize() throws Exception {

Statement lStatement = getConnection().getConnection()
.createStatement();

lStatement
.executeUpdate("CREATE TABLE PERSON (ID INT, NAME VARCHAR(60), FIRST_NAME VARCHAR(60), BIRTH_DATE DATE)");
}

/**
* Calls the {@link #initialize()} method on a new instance.
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {

new TableCreator().initialize();
}
}

In the above code we have create a table person in our testDB

Now letme create a GenericDAO which define any generic DAO contract

package com.linkwithweb.test.derby.dao;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;

/**
* A DAO interface with common methods.
*
* @param
* Object type of the DAO
* @param
* Object type of the unique key
* @author Ashwin
* @since 16th Nov 2010
*/
public interface IDao {

/**
* Returns the object denoted by this unique identifier in the back-end
* system.
*
* @param pId
* Unique identifier
* @return Object
* @throws SQLException
* If an error occurs
*/
T findById(K pId) throws SQLException;

/**
* Removes the object denoted by this unique identifier from the back-end
* system.
*
* @param pId
* Unique identifier
* @throws SQLException
* If an error occurs
*/
void removeById(K pId) throws SQLException;

/**
* Returns all the object in the back-end system.
*
* @return Collection of objects
* @throws SQLException
* If an error occurs
*/
Collection getAll() throws SQLException;
}

Now let me create Person DAO which acts on Person Table


package com.linkwithweb.test.derby.dao;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
* An abstract DAO that knows how to get a connection to the db.
*
* @param
* Object type of the DAO
* @param
* Object type of the unique key
* @author Ashwin
* @since 16th Nov 2010
*/
public abstract class AbstractDao implements
IDao {

/** Connection URL . */
private static final String CONNECTION_URL;

/** Connection login to the DB. */
private static final String CONNECTION_LOGIN;

/** Connection password to the DB. */
private static final String CONNECTION_PWD;

static {
CONNECTION_URL = System.getProperty("com.linkwithweb.url");
CONNECTION_LOGIN = System.getProperty("com.linkwithweb.login");
CONNECTION_PWD = System.getProperty("com.linkwithweb.pwd");
}

/**
* Gets a connection to the database.
*
*
* @return Connection
* @throws SQLException
* If the DB can't be connected to
*/
protected Connection createConnection() throws SQLException {

return DriverManager.getConnection(CONNECTION_URL, CONNECTION_LOGIN,
CONNECTION_PWD);
}
}

package com.linkwithweb.test.derby.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;

import com.linkwithweb.test.derby.model.Person;

/**
* DAO for accessing the datas of a person.
*
* @author Ashwin
* @since 16th Nov 2010
*/
public class PersonDao extends AbstractDao {

/**
* @throws SQLException
* @see com.linkwithweb.test.derby.dao.IDao#findById(java.lang.Object)
*/
public Person findById(Integer pId) throws SQLException {

Connection lConnection = null;

try {

lConnection = createConnection();

PreparedStatement lStatement = lConnection
.prepareStatement("SELECT * FROM PERSON WHERE ID = ?");

lStatement.setInt(1, pId);

ResultSet lRs = lStatement.executeQuery();

if (lRs.next()) {

Person lPerson = new Person();

lPerson.setId(lRs.getLong("ID"));
lPerson.setName(lRs.getString("NAME"));
lPerson.setFirstName(lRs.getString("FIRST_NAME"));
lPerson.setBirthDate(lRs.getDate("BIRTH_DATE"));

return lPerson;
}

} finally {

if (lConnection == null) {

lConnection.close();
}
}

return null;
}

/**
* @see com.linkwithweb.test.derby.dao.IDao#getAll()
*/
public Collection getAll() {
// TODO Auto-generated method stub
return null;
}

/**
* @see com.linkwithweb.test.derby.dao.IDao#removeById(java.lang.Object)
*/
public void removeById(Integer pId) {
// TODO Auto-generated method stub

}
}

Now as we have all the classes defined now. Let us create a PersonDAOTest which loads data into our person table and Does simple unit test

package com.linkwithweb.test.derby.dao;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;

import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.excel.XlsDataSet;
import org.dbunit.operation.DatabaseOperation;

import com.linkwithweb.test.derby.model.Person;

/**
* A test case for {@link PersonDao}.
*
* @author Ashwin
* @since 16th Nov 2010
*/
public class PersonDaoTest extends AbstractDaoTest {

/** The DAO to be tested. */
private PersonDao personDao;

/**
* @see org.dbunit.DatabaseTestCase#setUp()
*/
@Override
protected void setUp() throws Exception {

super.setUp();

// Creates the DAO to be tested
personDao = new PersonDao() {

/**
* @see com.linkwithweb.test.derby.dao.AbstractDao#createConnection()
*/
@Override
protected Connection createConnection() throws SQLException {

try {

return getConnection().getConnection();

} catch (Exception e) {

throw new SQLException(e);
}
}
};

InputStream lStream = PersonDaoTest.class.getClassLoader()
.getResourceAsStream("com/ashwin/test/derby/dao/person.xls");

// Creates the initialization data
IDataSet lDataSet = new XlsDataSet(lStream);

DatabaseOperation.CLEAN_INSERT.execute(getConnection(), lDataSet);
}

/**
* Test method for
* {@link com.linkwithweb.test.derby.dao.PersonDao#findById(java.lang.Integer)}.
*
* @throws SQLException
*/
public void testFindById() throws SQLException {

Person lPerson = personDao.findById(1);

assertNotNull(lPerson);
}
}

Below is the project structure which will give you an overview of how it is

C:\software\derby\src>tree /f
C:.
├───main
│ └───java
│ └───com
│ └───linkwithweb
│ └───test
│ └───derby
│ ├───dao
│ │ AbstractDao.java
│ │ IDao.java
│ │ PersonDao.java
│ │
│ └───model
│ Person.java

└───test
├───java
│ └───com
│ └───linkwithweb
│ └───test
│ └───derby
│ └───dao
│ AbstractDaoTest.java
│ PersonDaoTest.java
│ TableCreator.java

└───resources
└───com
└───linkwithweb
└───test
└───derby
└───dao
person.xls

DerbyHelloWorld
Rename to .rar