Showing posts with label Data. Show all posts
Showing posts with label Data. Show all posts

Thursday, March 8, 2012

Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 1)

Introduction

In this tutorial, we will create a simple CRUD application using Spring 3.1 and Neo4j. We will based this tutorial on a previous guide for MongoDB. This means we will re-use our existing design and implement only the data layer to use Neo4j as our data store.


Dependencies

  • Spring core 3.1.0.RELEASE
  • Spring Data Neo4j 2.1.0.M1
  • Neo4j Kernel 1.6
  • Neo4j Cypher 1.6
  • Neo4j Cypher DSL 1.6
  • See pom.xml for details

Github

To access the source code, please visit the project's Github repository (click here)

Functional Specs

Before we start, let's define our application's specification as follows:
  • A CRUD page for managing users
  • Use AJAX to avoid page refresh
  • Users have roles: either admin or regular (default)
  • Everyone can create new users and edit existing ones
  • When editing, users can only edit first name, last name, and role fields
  • A username is assumed to be unique

Here's our Use Case diagram:
[User]-(View)
[User]-(Add) 
[User]-(Edit) 
[User]-(Delete) 

Database

If you're new to Neo4j and Spring Data Neo4j and coming from a SQL-background, please take some time to read the following references:

In its simplest form, Neo4j is a NoSQL graph database containing nodes and relationships.

What is Neo4j?

The Neo4j data model consists of nodes and relationships, both of which can have key/value-style properties. What does that mean, exactly? Nodes are the graph database name for records, with property keys instead of column names. That's normal enough. Relationships are the special part. In Neo4j, relationships are first-class citizens, meaning they are more than a simple foreign-key reference to another record, relationships carry information.

Source: Spring Data Neo4j - Chapter 4. Learning Neo4j

What is a Graph database?

A graph database stores data in a graph, the most generic of data structures, capable of elegantly representing any kind of data in a highly accessible way.

“A Graph —records data in→ Nodes —which have→ Properties”

“Nodes —are organized by→ Relationships —which also have→ Properties”

“A Traversal —navigates→ a Graph; it —identifies→ Paths —which order→ Nodes”

“An Index —maps from→ Properties —to either→ Nodes or Relationships”

“A Graph Database —manages a→ Graph and —also manages related→ Indexes”


Source: What is a Graph Database?

From Java to Neo4j

We have two Java classes representing our domain: User and Role. Here is the Class diagram:

# Cool UML Diagram
[User|id;firstName;lastName;username;password;role{bg:orange}]1--1> [Role|id;role{bg:green}]

In Neo4j, User and Role are nodes, and the link between the two is a relationship. In Part 2 we will demonstrate how to declare them as nodes and how to create the relationship.

Here's the Activity diagram:

http://yuml.me/diagram/activity/(start)-%3E%3Cd1%3Eview-%3E(Show%20Records)-%3E%7Ca%7C-%3E(end),%20%3Cd1%3Eadd-%3E(Show%20Form)-%3E%7Ca%7C,%20%3Cd1%3Eedit-%3E%3Cd2%3Ehas%20selected-%3E(Show%20Form)-%3E%7Ca%7C,%20%3Cd2%3Eno%20record%20selected-%3E(Popup%20Alert)-%3E%7Ca%7C,%20%3Cd1%3Edelete-%3E%3Cd3%3Ehas%20selected-%3E(Delete%20Record)-%3E%7Ca%7C,%20%3Cd3%3Eno%20record%20selected-%3E(Popup%20Alert)-%3E%7Ca%7C.

Screenshots

Let's preview how the application will look like after it's finished. This is also a good way to clarify further our application's specs. Note: These are the same screenshots you will see from the Spring MVC 3.1 - Implement CRUD with Spring Data MongoDB guide (We're reusing the exact presentation layer).

Entry page
The entry page is the primary page that users will see. It contains a table showing user records and four buttons for adding, editing, deleting, and reloading data. All interactions will happen in this page.

Entry page

Edit existing record
When user clicks the Edit button, an Edit Record form shall appear after the table.

Edit record form

When a user submits the form, a success or failure alert should appear.

Success alert

When the operation is successful, the update record should reflect on the table.

Edited record appears on the table

Create new record
When a user clicks the New button, a Create New Record form shall appear after the table.

Create new record form

When a user submits the form, a success or failure alert should appear.

Success alert

When the operation is successful, the new record should appear on the table.

New record shows on the form

Delete record
When user clicks the Delete button, a success or failure alert should appear.

Success alert

Reload record
When user clicks the Reload button, the data on the table should be reloaded.

Errors
When user clicks the Edit or Delete button without selecting a record first, a "Select a record first!" alert should appear.

Error alert

Next

In the next section, we will write the Java classes and discuss the application's layers. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 1) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 2)

Review

In the previous section, we have laid down the functional specs of the application and discussed the Neo4j data model. In this section, we will discuss the project's structure, write the Java classes, and map our domain classes to the Neo4j data model.


Project Structure

Our application is a Maven project and therefore follows Maven structure. As we create the classes, we've organized them in logical layers: domain, repository, service, and controller.

Here's a preview of our project's structure:



The Layers

Domain Layer

This layer contains the following POJOs:
  • User - represents our user
  • Role - represents the role of the user
  • UserRoleRelationship - represents the relationship of a user to its role
  • .





Notice we've annotated our domain classes with Spring Data Neo4j annotations. Here are the explanations:

@NodeEntity

The @NodeEntity annotation is used to turn a POJO class into an entity backed by a node in the graph database. Fields on the entity are by default mapped to properties of the node. Fields referencing other node entities (or collections thereof) are linked with relationships.

Source: Spring Data Neo4j Reference

@GraphId

For the simple mapping this is a required field which must be of type Long. It is used by Spring Data Neo4j to store the node or relationship-id to re-connect the entity to the graph.

For the advanced mapping such a field is optional. Only if the underlying id has to be accessed, it is needed.

Source: Spring Data Neo4j Reference

@Indexed

@Indexed: Making entities searchable by field value

The @Indexed annotation can be declared on fields that are intended to be indexed by the Neo4j indexing facilities. The resulting index can be used to later retrieve nodes or relationships that contain a certain property value, e.g. a name. Often an index is used to establish the start node for a traversal.

Source: Spring Data Neo4j Reference

@Fetch

To have the collections of relationships being read eagerly ... we have to annotate it with the @Fetch annotation. Otherwise Spring Data Neo4j refrains from following relationships automatically.

Source: Spring Data Neo4j Reference

@RelatedTo

@RelatedTo: Connecting node entities

Every field of a node entity that references one or more other node entities is backed by relationships in the graph. These relationships are managed by Spring Data Neo4j automatically.

The simplest kind of relationship is a single field pointing to another node entity (1:1). In this case, the field does not have to be annotated at all, although the annotation may be used to control the direction and type of the relationship. When setting the field, a relationship is created when the entity is persisted. If the field is set to null, the relationship is removed.

Source: Spring Data Neo4j Reference

@RelationshipEntity

To access the full data model of graph relationships, POJOs can also be annotated with @RelationshipEntity, making them relationship entities. Just as node entities represent nodes in the graph, relationship entities represent relationships. As described above, fields annotated with @RelatedTo provide a way to link node entities together via relationships, but it provides no way of accessing the relationships themselves.

Relationship entities can be accessed via by @RelatedToVia-annotated

Fields in relationship entities are, similarly to node entities, persisted as properties on the relationship. For accessing the two endpoints of the relationship, two special annotations are available: @StartNode and @EndNode. A field annotated with one of these annotations will provide read-only access to the corresponding endpoint, depending on the chosen annotation.

Source: Spring Data Neo4j Reference

Controller Layer

This layer contains two controllers, MediatorController and UserController
  • MediatorController is responsible for redirecting requests to appropriate pages. This isn't really required but it's here for organizational purposes.
  • UserController is responsible for handling user-related requests such as adding and deleting of records



Service Layer

This layer contains a single service, UserService for managing users.



What is Spring Data Neo4j?

Spring Data Neo4j enables POJO based development for the Graph Database Neo4j. It maps annotated entity classes to the Neo4j Graph Database with advanced mapping functionality. The template programming model is equivalent to well known Spring templates and builds the basis for interaction with the graph and is also used for the advanced repository support.
Spring Data Neo4j is part of the Spring Data project which aims to provide convenient support for NoSQL databases.

Source: http://www.springsource.org/spring-data/neo4j

Utility classes

TraceInterceptor class is an AOP-based utility class to help us debug our application. This is a subclass of CustomizableTraceInterceptor (see Spring Data JPA FAQ)



Next

In the next section, we will focus on the configuration files for enabling Spring MVC. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 2) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 3)

Review

In the previous section, we have implemented the Java classes and discussed the Neo4j service. In this section, we will write the configuration files for enabling Spring MVC and Neo4j support.


Configuration

To enable Neo4j support, we need to declare the following beans
  • a Spring Data Neo4j repository
  • a Neo4j store directory
  • Optionally, we declared an InitNeo4jService to automatically populate our database with sample data (currently disabled)


Finally, here's our applicationContext.xml file

Next

In the next section, we will create the HTML and JavaScript files. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 3) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 4)

Review

In the previous section, we have created the configuration files and discussed them accordingly. In this section, we will focus on the view layer, in particular the HTML files and JavaScript codes.


HTML Files (with AJAX)

To improve the user experience, we will use AJAX to make the application responsive. All actions will be performed on the same page (no page refresh). Consequently, we only have one HTML page for the entire application. The rest are JavaScript files.

Notice how we've structured the HTML page. Basically, we followed the concept of separation of concerns by separating markup tags, CSS, and JavaScript code. We tried as much as possible to make the JavaScript code and CSS styles unobtrusive.



A Closer Look

At first glance, this JSP file seems complex. On the contrary, it's quite simple. Let's break it into smaller pieces for clarity:

URLs
The following declares our URLs as mapped to our UserController. We're using the url taglib to make the URL portable.


Imports
Here we're importing custom CSS and JavaScript files, along with jQuery.


What is jQuery?
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

Source: http://jquery.com/

JavaScript initialization
Here we're preparing the URLs, attaching functions to our buttons, and initially loading the table. The main chunk of the JavaScript code is referenced from an external JavaScript file custom.js
  • loadTable(): Performs an AJAX request and populates our table with records
  • toggleForms(): Hides and shows specific forms based on the passed argument
  • toggleCrudButtons(): Hides and shows buttons
  • hasSelected(): Checks whether a record has been selected
  • fillEditForm(): Fills the Edit form with details based on the selected record
  • submitDeleteRecord(): Submits a delete request via AJAX
  • submitNewRecord(): Submits a create new record request via AJAX
  • submitUpdateRecord(): Submits an update record request via AJAX


Table and buttons
This is a simple table for displaying records. The buttons are for interacting with the data.


Forms
These are forms used when adding and editing records.


Preview

If we run our application, this is what we shall see:

Entry page

For more screenshots, please visit Part 1 of this tutorial and check the Screenshots section.

Next

In the next section, we will build and run the application using Maven, and show how to import the project in Eclipse. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 4) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 5)

Review

We have just completed our application! In the previous sections, we have discussed the functional specs, created the Java classes, declared the configuration files, and wrote the HTML files. In this section, we will build and run the application using Maven, and show how to import the project in Eclipse.


Running the Application

Access the source code

To download the source code, please visit the project's Github repository (click here)

Preparing the data source

  • You don't need to run a separate Neo4j server because it will start simultaneously with the application.
  • There's no need to populate the database.
  • Due to some issues with the initialization service, I have decided to deactivate the service (though it's included in the source code for reference).

Building with Maven

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn tomcat:run
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'tomcat'.
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from central
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from snapshots
    [INFO] ------------------------------------------
    [INFO] Building spring-neo4j-tutorial Maven Webapp
    [INFO]    task-segment: [tomcat:run]
    [INFO] ------------------------------------------
    [INFO] Preparing tomcat:run
    [INFO] [apt:process {execution: default}]
    [INFO] [resources:resources {execution: default-resources}]
    [INFO] [tomcat:run {execution: default-cli}]
    [INFO] Running war on http://localhost:8080/spring-neo4j-tutorial
    Mar 9, 2012 7:19:07 AM org.apache.catalina.startup.Embedded start
    INFO: Starting tomcat server
    Mar 9, 2012 7:19:07 AM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
    Mar 9, 2012 7:19:07 AM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    Mar 9, 2012 7:19:11 AM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Mar 9, 2012 7:19:11 AM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    
  5. Note: If the project will not build due to missing repositories, please enable the repositories section in the pom.xml!

Access the Entry page

  1. Follow the steps with Building with Maven
  2. Open a browser
  3. Enter the following URL (8080 is the default port for Tomcat):
    http://localhost:8080/spring-neo4j-tutorial/

Import the project in Eclipse

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn eclipse:eclipse -Dwtpversion=2.0
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'eclipse'.
    [INFO] org.apache.maven.plugins: checking for updates from central
    [INFO] org.apache.maven.plugins: checking for updates from snapshots
    [INFO] org.codehaus.mojo: checking for updates from central
    [INFO] org.codehaus.mojo: checking for updates from snapshots
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from central
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from snapshots
    [INFO] -----------------------------------------
    [INFO] Building spring-neo4j-tutorial Maven Webapp
    [INFO]    task-segment: [eclipse:eclipse]
    [INFO] -----------------------------------------
    [INFO] Preparing eclipse:eclipse
    [INFO] No goals needed for project - skipping
    [INFO] [eclipse:eclipse {execution: default-cli}]
    [INFO] Adding support for WTP version 2.0.
    [INFO] -----------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] -----------------------------------------
    
    This command will add the following files to your project:
    .classpath
    .project
    .settings
    target
    You may have to enable "show hidden files" in your file explorer to view them
  5. Open Eclipse and import the project

Conclusion

That's it! We've have successfully completed our Spring MVC 3.1 web application. We've learned how to integrate Neo4j using the Spring Data Neo4j framework, and studied how to map our domain objects to the Neo4j graph. We've only explored the basics of Neo4j, but I hope that this simple tutorial will provide a good start.

I hope you've enjoyed this tutorial. Don't forget to check my other tutorials at the Tutorials section.

Revision History


Revision Date Description
1 March 8 2012 Uploaded tutorial
2 March 9 2012 Uploaded source code to Github

StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Neo4j (Part 5) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Wednesday, February 8, 2012

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 1)

In this tutorial, we will create a simple CRUD application using Spring 3.1 and Redis. We will based this tutorial on a previous guide for MongoDB: Spring MVC 3.1 - Implement CRUD with Spring Data MongoDB. This means we will re-use our existing design and implement only the data layer to use Redis as our data store.


Dependencies

  • Spring core 3.1.0.RELEASE
  • Spring Data Redis 1.0.0.RC1
  • Redis (server) 2.4.7
  • See pom.xml for details

Github

To access the source code, please visit the project's Github repository (click here)

Functional Specs

Before we start, let's define our application's specs as follows:
  • A CRUD page for managing users
  • Use AJAX to avoid page refresh
  • Users have roles: either admin or regular (default)
  • Everyone can create new users and edit existing ones
  • When editing, users can only edit first name, last name, and role fields
  • A username is assumed to be unique

Here's our Use Case diagram:
[User]-(View)
[User]-(Add) 
[User]-(Edit) 
[User]-(Delete) 

Database

If you're new to Redis and coming from a SQL-background, please take some time to read the Redis Official Documentation. I would like to put emphasis on studying the Redis data types. See Data types and A fifteen minute introduction to Redis data types.

In its purest form, Redis is a key-value store that can support various data structures: Strings, Sets, Lists, Hashes, and Sorted Sets. Among these structures, we will pay extra attention to Hashes because we can use it to represent Java objects.

Hashes

Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects (eg: A User with a number of fields like name, surname, age, and so forth):

Source: Data types

From Java to Redis

We have two Java classes representing our domain: User and Role. Here is the Class diagram:

# Cool UML Diagram
[User|id;firstName;lastName;username;password;role{bg:orange}]1--1> [Role|id;role{bg:green}]

However, Redis is a key-value store, and we can already see the model mismatch. How do we exactly map a Java class to a Redis structure? One of way of dealing with this is to use Hash structure.

Assume we have the following User object with the following properties:
User
----
id = 1
username = john
password = 12345678
role = 1

To map this object to Redis, via the command-line tool, as a Hash structure we use the command HMSET:
redis> HMSET user:1 id 1 username john password 12345678 role 1
"OK"

redis> HGETALL user:1
{"id":"1","username":"john","password":"12345678","role":"1"}

In this example, user:1 becomes the column name and the id (if we think of this in terms of a relational database). Notice we don't have to map a Role object because we've already set the value along with the user key.

Try Redis

If you need to experiment with an actual Redis instance online, visit the Try Redis.


Screenshots

Let's preview how the application will look like after it's finished. This is also a good way to clarify further the application's specs. Note: These are the same screenshots you will see from the Spring MVC 3.1 - Implement CRUD with Spring Data MongoDB guide.

The Activity diagram:

http://yuml.me/diagram/activity/(start)-%3E%3Cd1%3Eview-%3E(Show%20Records)-%3E%7Ca%7C-%3E(end),%20%3Cd1%3Eadd-%3E(Show%20Form)-%3E%7Ca%7C,%20%3Cd1%3Eedit-%3E%3Cd2%3Ehas%20selected-%3E(Show%20Form)-%3E%7Ca%7C,%20%3Cd2%3Eno%20record%20selected-%3E(Popup%20Alert)-%3E%7Ca%7C,%20%3Cd1%3Edelete-%3E%3Cd3%3Ehas%20selected-%3E(Delete%20Record)-%3E%7Ca%7C,%20%3Cd3%3Eno%20record%20selected-%3E(Popup%20Alert)-%3E%7Ca%7C.

Entry page
The entry page is the primary page that users will see. It contains a table showing user records and four buttons for adding, editing, deleting, and reloading data. All interactions will happen in this page.

Entry page

Edit existing record
When user clicks the Edit button, an Edit Record form shall appear after the table.

Edit record form

When a user submits the form, a success or failure alert should appear.

Success alert

When the operation is successful, the update record should reflect on the table.

Edited record appears on the table

Create new record
When a user clicks the New button, a Create New Record form shall appear after the table.

Create new record form

When a user submits the form, a success or failure alert should appear.

Success alert

When the operation is successful, the new record should appear on the table.

New record shows on the form

Delete record
When user clicks the Delete button, a success or failure alert should appear.

Success alert

Reload record
When user clicks the Reload button, the data on the table should be reloaded.

Errors
When user clicks the Edit or Delete button without selecting a record first, a "Select a record first!" alert should appear.

Error alert

Next

In the next section, we will study how to setup a Redis server both in Windows and Ubuntu. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 1) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 2)

Review

In the previous section, we have laid down the functional specs of the application and studied how to map a Java object to a Redis data structure. In this section, we will study how to setup a Redis server both in Windows and Ubuntu.


Redis Setup

We will demonstrate first how to setup Redis in Windows 7, then on Ubuntu 10.04.

Windows 7

To setup a Redis server in Windows, follow these steps:

1. Open a browser and visit the Redis download section at http://redis.io/download

2. Choose the Win32/64 download. Notice it's status is Unofficial because the Redis project does not directly support win32/win64


3. Although Windows is not officially supported, there's a port available for it by Dušan Majkić. Under the Win32/64 section, click on the link A Native win32/win64 port created by Dušan Majkić.. It will bring you to a Github page.

4. Click on the Downloads section (upper-right) and you should see the following downloads.


5. Download the latest one (currently, it's 2.4.5).

6. Once the download is finished, extract the contents. Open the new folder and browse under the 32bit folder (choose 64bit if you have Windows 64bit version).




7. To run a Redis server, double-click the redis-server.exe


You should see the following console stating that Redis is now running:


To run a client interface, double-click the redis-cli.exe


And you should see the following console--waiting for your command:


Ubuntu 10.04

To setup a Redis server in Ubuntu, you will need to build it from the source. There are two ways:
  • Manual download
  • Terminal-based

Manual download

1. Open a browser and visit the Redis download section at http://redis.io/download

2. Download the latest and stable version (currently at 2.4.7).

3. Once the download is finished, extract the contents.

4. Now, let's build the source. Open a terminal and enter the following command:
/REDIS-DOWNLOAD-PATH/make


After building Redis, test it using the following command (make sure to replace REDIS-DOWNLOAD-PATH accordingly):
/REDIS-DOWNLOAD-PATH/make test


5. The binaries that are now compiled are available in the src directory. Run Redis with:
/REDIS-DOWNLOAD-PATH/src/redis-server


Terminal-based

1. Download, extract and compile Redis with:
$ wget http://redis.googlecode.com/files/redis-2.4.7.tar.gz
$ tar xzf redis-2.4.7.tar.gz
$ cd redis-2.4.7
$ make


2. The binaries that are now compiled are available in the src directory. Run Redis with:
$ src/redis-server


Note: These are the same steps you will see under the Download section at http://redis.io/download

Next

In the next section, we will discuss the project's structure and start writing the Java classes. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 2) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 3)

Review

In the previous section, we have learned how to setup a Redis server in Windows and Ubuntu. In this section, we will discuss the project's structure and write the Java classes.


Project Structure

Our application is a Maven project and therefore follows Maven structure. As we create the classes, we've organized them in logical layers: domain, repository, service, and controller.

Here's a preview of our project's structure:

Note: You might have noticed ignore an error icon in the jQuery file. This is an Eclipse validation issue. You can safely ignore this error.

The Layers

Domain Layer

This layer contains two POJOs, User and Role.




Controller Layer

This layer contains two controllers, MediatorController and UserController
  • MediatorController is responsible for redirecting requests to appropriate pages. This isn't really required but it's here for organizational purposes.
  • UserController is responsible for handling user-related requests such as adding and deleting of records



Service Layer

This layer contains two services, UserService and InitRedisService
  • UserService is our CRUD service for managing users
  • InitRedisService is used for initiliazing our database with sample data using the RedisTemplate



As mentioned in Part 1, we shall use Hashes to store Java objects in Redis. With the help of Spring Data for Redis, in particular the RedisTemplate, we're able to perform various Redis operations.

To access Hash operations using RedisTemplate, we use the following syntax:
template.opsForHash()
template.opsForHash().put
template.opsForHash().delete


To keep track of our users, we will use Set data structure for Redis
template.opsForSet()
template.opsForSet().add
template.opsForSet().remove


What is Spring Data Redis?

Spring Data for Redis is part of the umbrella Spring Data project which provides support for writing Redis applications. The Spring framework has always promoted a POJO programming model with a strong emphasis on portability and productivity. These values are carried over into Spring Data for Redis.

Source: http://www.springsource.org/spring-data/redis

Utility classes

TraceInterceptor class is an AOP-based utility class to help us debug our application. This is a subclass of CustomizableTraceInterceptor (see Spring Data JPA FAQ)



Next

In the next section, we will focus on the configuration files for enabling Spring MVC. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 3) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 4)

Review

In the previous section, we have implemented the Java classes and discussed the Redis service. In this section, we will write the configuration files for enabling Spring MVC and Redis support.


Configuration

To enable Redis support, we need to declare the following beans
  • a Redis connection factory
  • a Redis template
  • Optionally, we declared an InitRedisService to automatically populate our database with sample data


Finally, here's our applicationContext.xml file

Next

In the next section, we will create the HTML and JavaScript files. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 4) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 6)

Review

We have just completed our application! In the previous sections, we have discussed the functional specs, created the Java classes, declared the configuration files, and wrote the HTMl files. In this section, we will build and run the application using Maven, and show how to import the project in Eclipse.


Running the Application

Access the source code

To download the source code, please visit the project's Github repository (click here)

Preparing the data source

  1. Run Redis (see Part 2 for instructions)
  2. There's no need to populate the database with sample data because our InitRedisService will insert our sample data automatically

Building with Maven

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn tomcat:run
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'tomcat'.
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from central
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from snapshots
    [INFO] ------------------------------------------
    [INFO] Building spring-redis-tutorial Maven Webapp
    [INFO]    task-segment: [tomcat:run]
    [INFO] ------------------------------------------
    [INFO] Preparing tomcat:run
    [INFO] [apt:process {execution: default}]
    [INFO] [resources:resources {execution: default-resources}]
    [INFO] [tomcat:run {execution: default-cli}]
    [INFO] Running war on http://localhost:8080/spring-redis-tutorial
    Feb 8, 2012 8:57:04 PM org.apache.catalina.startup.Embedded start
    INFO: Starting tomcat server
    Feb 8, 2012 8:57:04 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
    Feb 8, 2012 8:57:05 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    Feb 8, 2012 8:57:07 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Feb 8, 2012 8:57:07 PM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    
  5. Note: If the project will not build due to missing repositories, please enable the repositories section in the pom.xml!

Access the Entry page

  1. Follow the steps with Building with Maven
  2. Open a browser
  3. Enter the following URL (8080 is the default port for Tomcat):
    http://localhost:8080/spring-redis-tutorial/

Import the project in Eclipse

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn eclipse:eclipse -Dwtpversion=2.0
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'eclipse'.
    [INFO] org.apache.maven.plugins: checking for updates from central
    [INFO] org.apache.maven.plugins: checking for updates from snapshots
    [INFO] org.codehaus.mojo: checking for updates from central
    [INFO] org.codehaus.mojo: checking for updates from snapshots
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from central
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from snapshots
    [INFO] -----------------------------------------
    [INFO] Building spring-redis-tutorial Maven Webapp
    [INFO]    task-segment: [eclipse:eclipse]
    [INFO] -----------------------------------------
    [INFO] Preparing eclipse:eclipse
    [INFO] No goals needed for project - skipping
    [INFO] [eclipse:eclipse {execution: default-cli}]
    [INFO] Adding support for WTP version 2.0.
    [INFO] -----------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] -----------------------------------------
    
    This command will add the following files to your project:
    .classpath
    .project
    .settings
    target
    You may have to enable "show hidden files" in your file explorer to view them
  5. Open Eclipse and import the project

Conclusion

That's it! We've have successfully completed our Spring MVC 3.1 web application. We've learned how to setup Redis and access it through Spring Data Redis. Furthermore, we used AJAX to make the application responsive.

I hope you've enjoyed this tutorial. Don't forget to check my other tutorials at the Tutorials section.

Revision History


Revision Date Description
1 Feb 8 2012 Uploaded tutorial and Github repository

StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 6) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 5)

Review

In the previous section, we have created the configuration files and discussed them accordingly. In this section, we will focus on the view layer, in particular the HTML files and JavaScript codes.


HTML Files (with AJAX)

To improve the user experience, we will use AJAX to make the application responsive. All actions will be performed on the same page (no page refresh). Consequently, we only have one HTML page for the entire application. The rest are JavaScript files.

Notice how we've structured the HTML page. Basically, we followed the concept of separation of concerns by separating markup tags, CSS, and JavaScript code. We tried as much as possible to make the JavaScript code and CSS styles unobtrusive.



A Closer Look

At first glance, this JSP file seems complex. On the contrary, it's quite simple. Let's break it into smaller pieces for clarity:

URLs
The following declares our URLs as mapped to our UserController. We're using the url taglib to make the URL portable.


Imports
Here we're importing custom CSS and JavaScript files, along with jQuery.


What is jQuery?
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

Source: http://jquery.com/

JavaScript initialization
Here we're preparing the URLs, attaching functions to our buttons, and initially loading the table. The main chunk of the JavaScript code is referenced from an external JavaScript file custom.js
  • loadTable(): Performs an AJAX request and populates our table with records
  • toggleForms(): Hides and shows specific forms based on the passed argument
  • toggleCrudButtons(): Hides and shows buttons
  • hasSelected(): Checks whether a record has been selected
  • fillEditForm(): Fills the Edit form with details based on the selected record
  • submitDeleteRecord(): Submits a delete request via AJAX
  • submitNewRecord(): Submits a create new record request via AJAX
  • submitUpdateRecord(): Submits an update record request via AJAX


Table and buttons
This is a simple table for displaying records. The buttons are for interacting with the data.


Forms
These are forms used when adding and editing records.


Preview

If we run our application, this is what we shall see:

Entry page

For more screenshots, please visit Part 1 of this tutorial and check the Screenshots section.

Next

In the next section, we will build and run the application using Maven, and show how to import the project in Eclipse. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 5) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Tuesday, January 31, 2012

Spring MVC 3.1 and JasperReports: Using iReport and AJAX (Part 1)

In this tutorial, we will study how to generate reports from a Spring MVC 3.1 application using JasperReports. We will use jQuery and jqGrid to provide AJAX support and an interactive table. To design the report, we will use iReport, an open source report designer for JasperReports. On the data layer, we'll utilize MySQL, Hibernate, and Spring Data JPA.


Dependencies

  • Spring core 3.1.0.RELEASE
  • Spring Data JPA 1.1.0.M1
  • jQuery 1.6.4
  • jqGrid 4.3.1
  • Jasper Reports 4.5.0
  • See pom.xml for details

Github

To access the source code, please visit the project's Github repository (click here)

Functional Specs

Before we start, let's define our application's specs as follows:
  • Display reports in an interactive table
  • Downloadable reports in PDF and Excel formats
  • Use AJAX to avoid page refresh
  • Users have roles. They are either admin or regular (default)
  • A username is assumed to be unique

Here's our Use Case diagram:
[User]-(View)
[User]-(Download Pdf) 
[User]-(Download Excel)

Database

Our database contains two tables: user and role tables.


user and role table design

User table

The user table contains personal information of each user. Notice the password values are hashed using Md5.

user table

Role table

The role table contains role values of each user. We define a role value of 1 as an admin, while a role value of 2 as a regular user.

role table

Screenshots

Before we start with the actual development, let's preview how our application will look like. This is also a good way to clarify further the application's specs.

Entry page
The entry page is the primary page that users will see. It contains an interactive table where users can view and download records.
Entry page

Pdf document
This is the downloadable Pdf document whenever the user clicks on the Pdf button.
Report in Pdf format as previewed from Chrome

Excel document
This is the downloadable Excel document whenever the user clicks on the Excel button. When using Excel format, the document's appearance varies depending on the application, i.e Microsoft Excel, Google Docs, Open Office.
Report in Excel format as previewed from Google Docs

Progress dialog
When a user clicks on any of the download buttons (Pdf or Excel), a progress dialog will appear and disappears once the download starts.
Progress alert


Next

In the next section, we will discuss the project's structure and write the Java classes. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 and JasperReports: Using iReport and AJAX (Part 1) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share