Spring Data JPA to persist the domain objects

Hi all,These days i am taking little time to post new topics as i am doing little R&D in spring’s latest projects like ‘SpringBoot’ and ‘SpringData’. Now here is the post which will explain about ‘SpringData’. Please follow the code little carefully as i wrote block comments in order to better understand the logic. this project is designed under Maven,Spring4.1.1.RELEASE, Eclipse Luna and Tomcat 8.0.11.

Please find the below is the project structure, First let us start with required dependencies for the project as shown below.
project_structure
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.spark.spring.data.rest</groupId>
	<artifactId>SpringDataRest</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringDataRest</name>
	<description>SpringDataRest</description>
	
	<repositories>
		<repository>
			<id>repository.jboss.org-public</id>
			<name>JBoss repository</name>
			<url>https://repository.jboss.org/nexus/content/groups/public</url>
		</repository>
	</repositories>
	<properties>
		<hibernate.version>4.0.1.Final</hibernate.version>
		<mysql.connector.version>5.1.9</mysql.connector.version>
		<slf4j.version>1.6.1</slf4j.version>
		<spring.version>4.1.1.RELEASE</spring.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<!-- Spring Framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- Spring MVC -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>
		<!-- Spring Data JPA -->
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-jpa</artifactId>
			<version>1.0.2.RELEASE</version>
		</dependency>
		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.0.1.GA</version>
		</dependency>

		<!-- H2 Database -->
		<!-- <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> 
			<version>1.3.160</version> </dependency> -->
		<!-- MySQL JDBC connector -->
		<!-- If you want to use MySQL, uncomment this dependency declation. -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.connector.version}</version>
		</dependency>
		<!-- PostgreSQL JDBC 4 -->
		<!-- If you don't want to use PostgreSQL, uncomment this dependency declaration. -->
		<!-- <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> 
			<version>9.0-801.jdbc4</version> </dependency> -->
		<!-- BoneCP -->
		<dependency>
			<groupId>com.jolbox</groupId>
			<artifactId>bonecp</artifactId>
			<version>0.7.1.RELEASE</version>
		</dependency>
		<!-- Servlet API 3.0 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!-- Logging dependencies -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>
		<!-- Testing Dependencies -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.9</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>SpringData</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.1.1</version>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Let us carry on with all the configurations required by the project and then with the actual logic. below is the code for the ‘application.properties’ file and ‘applicationContext.xml’
application.properties this file is fully loaded with all properties which are required by major databases, just uncomment what ever you need and use it.

# The default database is H2 memory database but I have also
# added configuration needed to use either MySQL and PostgreSQL.
 
#Database Configuration

#db.driver=org.h2.Driver
db.driver=com.mysql.jdbc.Driver
#db.driver=org.postgresql.Driver
#db.driver=oralce.jdbc.driver.OracleDriver

#db.url=jdbc:h2:mem:datajpa
db.url=jdbc:mysql://localhost:3306/test
#db.url=jdbc:postgresql://localhost/datajpa
#db.url=jdbc:oracle:thin:@localhost:1521:xe

db.username=?
db.password=?
 
#Hibernate Configuration
#hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.dialect=org.hibernate.dialect.MySQLDialect
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

hibernate.format_sql=true
hibernate.ejb.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
hibernate.show_sql=true
 
#MessageSource
message.source.basename=i18n/messages
message.source.use.code.as.default.message=true
 
#EntityManager
#Declares the base package of the entity classes
entitymanager.packages.to.scan=com.spark.spring.data.domain

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
	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-3.1.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
	
	<!-- Configures the location of static resources such as css files. Requires 
		Spring Framework 3.0 or higher. -->
	<mvc:resources mapping="/static/**" location="/static/" />

	<!-- Ensures that dispatcher servlet can be mapped to '/' and static resources 
		are still served by the containers default servlet. Requires Spring Framework 
		3.0 or higher. -->
	<mvc:default-servlet-handler />

	<!-- Configures Spring Data JPA and sets the base package of repositories. -->
	<jpa:repositories base-package="com.spark.spring.data.repositories" />

</beans>

Now it is time for us to write Java Configurations for Spring to initialize various bean objects and to recognize various annotations in the project, also let us write a configuration for servlet initialization instead of traditional web.xml

ApplicationConfig.java : this class is responsible for initialising the DataSource,JpaTransactionManager and for setting Hibernate properties

/**
 * 
 */
package com.spark.spring.data.config;

import java.util.Properties;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.hibernate.ejb.HibernatePersistence;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * An application context Java configuration class. The usage of Java configuration
 * requires Spring Framework 3.0 or higher with following exceptions:
 * <ul>
 *     <li>@EnableWebMvc annotation requires Spring Framework 3.1</li>
 * </ul>
 * @author Pavan Kumar Mantha
 */
@Configuration
@ComponentScan(basePackages = {"com.spark.spring.data"})
@EnableWebMvc
@ImportResource("classpath:applicationContext.xml")
@PropertySource("classpath:application.properties")
public class ApplicationConfig {

	private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/jsp/";
    private static final String VIEW_RESOLVER_SUFFIX = ".jsp";
 
    private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
    private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
    private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
    private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
 
    private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
    private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
    private static final String PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY = "hibernate.ejb.naming_strategy";
    private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
    private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
 
    @Resource
    private Environment environment;
    
    @Bean
    public DataSource getDataSource(){
    	DriverManagerDataSource dataSource = new DriverManagerDataSource();
    	dataSource.setDriverClassName(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
        dataSource.setUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
        dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
        dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
 
        return dataSource;
    }
    
    @Bean(name="transactionManager")
    public JpaTransactionManager getJpaTransactionManager() throws ClassNotFoundException{
    	JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
    	jpaTransactionManager.setEntityManagerFactory(getLocalEntityManagerFactoryBean().getObject());
    	return jpaTransactionManager;
    }
    
    @Bean
    public LocalContainerEntityManagerFactoryBean getLocalEntityManagerFactoryBean(){
    	LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
    	entityManagerFactoryBean.setDataSource(getDataSource());
    	entityManagerFactoryBean.setPackagesToScan(environment.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
    	entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
    	
    	Properties properties = new Properties();
    	properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
    	properties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
    	properties.put(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_NAMING_STRATEGY));
    	properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, environment.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
    	
    	entityManagerFactoryBean.setJpaProperties(properties);
    	return entityManagerFactoryBean;
    }
    
    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
 
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix(VIEW_RESOLVER_PREFIX);
        viewResolver.setSuffix(VIEW_RESOLVER_SUFFIX);
 
        return viewResolver;
    }
}

WebContextInit.java : This class is responsible for initializing the servlet(front controller) and remember this will only work with servlet 3 containers only.

/**
 * 
 */
package com.spark.spring.data.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * Web application Java configuration class. The usage of web application
 * initializer requires Spring Framework 3.1 and Servlet 3.0.
 * @author Pavan kumar Mantha
 */
public class WebContextInit implements WebApplicationInitializer {

	private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
	private static final String DISPATCHER_SERVLET_MAPPING = "/rest/*";

	@Override
	public void onStartup(ServletContext servletContext)
			throws ServletException {
		AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
		annotationConfigWebApplicationContext.register(ApplicationConfig.class);

		ServletRegistration.Dynamic dynamic = servletContext.addServlet(
				DISPATCHER_SERVLET_NAME, new DispatcherServlet(
						annotationConfigWebApplicationContext));
		dynamic.setLoadOnStartup(1);
		dynamic.addMapping(DISPATCHER_SERVLET_MAPPING);
		
	}

}

Now let us design our domain objects, data transfer objects and User defined Exceptions. In this case our domain object is “Person.java”. in this class we have a static inner class which is called “Builder”, the responsibility of Builder class is to create Person objects and return them.
Person.java

/**
 * 
 */
package com.spark.spring.data.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;

/**
 * An entity class which contains the information of a single person.
 * 
 * @author Pavan kumar Mantha
 */
@Entity
@Table(name = "person")
public class Person {
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	@Column(name = "first_name", nullable = false)
	private String firstName;

	@Column(name = "last_name", nullable = false)
	private String lastName;

	@Version
	private long version = 0;

	/**
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the version
	 */
	public long getVersion() {
		return version;
	}

	/**
	 * @param version
	 *            the version to set
	 */
	public void setVersion(long version) {
		this.version = version;
	}
	
	/**
	 * this method returns the builder object
	 */
	public static Builder getBuilder(String firstName,String lastName){
		return new Builder(firstName, lastName);
	}
	
	/**
	 * A Builder class that is used to create Person Object.
	 */
	public static class Builder{
		
		Person person;
		
		public Builder(String firstName, String lastName) {
			person = new Person();
			person.firstName = firstName;
			person.lastName = lastName;
		}
		
		public Person build(){
			return person;
		}
	}

}

PersonDTO.java : This class is responsible to inject the data from the front end and then push that to builder class and get the original person domain object

/**
 * 
 */
package com.spark.spring.data.domain;

import org.hibernate.validator.constraints.NotEmpty;

/**
 * A DTO object which is used as a form object
 * in create person and edit person forms.
 * @author Pavan Kumar Mantha
 */
public class PersonDTO {

	private Long id;

	@NotEmpty
	private String firstName;

	@NotEmpty
	private String lastName;

	public PersonDTO() {

	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

}

PersonNotFoundException.java

/**
 * 
 */
package com.spark.spring.data.exceptions;

/**
 * @author Pavan Kumar mantha
 *
 */
public class PersonNotFoundException extends Exception{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public PersonNotFoundException() {
		super();
	}
	
	@Override
	public synchronized Throwable getCause() {
		return super.getCause();
	}
	
	@Override
	public String getMessage() {
		return super.getMessage();
	}
}

Since all our Domain Objects,DTO objects and custom exception types are in place, its time for us to write our Repository Interface. Spring Data has given an out of the box functionality for CRUD operations called CRUDRepository and there are many other Repositories which will extend from this base interface and one of them is “JpaRepository”. It is prety straight forward to design a repository all you have to do is to create an interface which extends the JpaRepository interface. The JpaRepository interface is a JPA specific extension to the Repository interface and it gives you the access to following methods which are used to implement the CRUD application:

delete(T entity) which deletes the entity given as a parameter.
findAll() which returns a list of entities.
findOne(ID id) which returns the entity using the id given a parameter as a search criteria.
save(T entity) which saves the entity given as a parameter.

PersonRepository.java

/**
 * 
 */
package com.spark.spring.data.repositories;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.spark.spring.data.domain.Person;

/**
 * Specifies methods used to obtain and modify person related information
 * which is stored in the database.
 * @author Pavan Kumar Mantha
 */
@Transactional(value="transactionManager",propagation=Propagation.NESTED)
public interface PersonRepository extends JpaRepository<Person, Long>{

}

Once we have our PersonRepository interface ready to use, let us start with service layer to hadle the business logic.
PersonService.java : This interface is responsible for basic operations on the domain object in connection with the underlying database.

/**
 * 
 */
package com.spark.spring.data.service;

import java.util.List;

import com.spark.spring.data.domain.Person;
import com.spark.spring.data.domain.PersonDTO;
import com.spark.spring.data.exceptions.PersonNotFoundException;

/**
 * Declares methods used to obtain and modify person information.
 * @author Pavan Kumar Mantha
 */
public interface PersonService {

	/**
     * Creates a new person.
     * @param created   The information of the created person.
     * @return  The created person.
     */
    public Person create(PersonDTO personDTO);
 
    /**
     * Deletes a person.
     * @param personId  The id of the deleted person.
     * @return  The deleted person.
     * @throws PersonNotFoundException  if no person is found with the given id.
     */
    public Person delete(Long personId) throws PersonNotFoundException;
 
    /**
     * Finds all persons.
     * @return  A list of persons.
     */
    public List<Person> findAll();
 
    /**
     * Finds person by id.
     * @param id    The id of the wanted person.
     * @return  The found person. If no person is found, this method returns null.
     */
    public Person findById(Long id);
 
    /**
     * Updates the information of a person.
     * @param updated   The information of the updated person.
     * @return  The updated person.
     * @throws PersonNotFoundException  if no person is found with given id.
     */
    public Person update(PersonDTO personDTO) throws PersonNotFoundException;
}

The implmentation for the above service interface is as below.
Note : all the methods of interface are implemented with default definition and only create has the exact logic, the others are left for you people to implement.Also observer @Transactional annotation it is at the method level not at the class level.
Please observer that the PersonRepository class gets injected by the spring container and CRUD operation capability is provided by it.
PersonServiceImpl.java

/**
 * 
 */
package com.spark.spring.data.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spark.spring.data.domain.Person;
import com.spark.spring.data.domain.PersonDTO;
import com.spark.spring.data.exceptions.PersonNotFoundException;
import com.spark.spring.data.repositories.PersonRepository;
import com.spark.spring.data.service.PersonService;

/**
 * This implementation of the PersonService interface communicates with
 * the database by using a Spring Data JPA repository.
 * @author Pavan Kumar Mantha
 */
@Service(value="personService")
public class PersonServiceImpl implements PersonService{

	@Resource
	private PersonRepository personRepository;
	
	@Override
	@Transactional(value="transactionManager")
	public Person create(PersonDTO personDTO) {

		Person person = Person.getBuilder(personDTO.getFirstName(), personDTO.getLastName()).build();
		return personRepository.save(person);
	}

	@Override
	public Person delete(Long personId) throws PersonNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Person> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Person findById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Person update(PersonDTO personDTO) throws PersonNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

}

Now every thing is completed from logic point of view let us start with the controller class class to handle different request from client.
Please observe that i have hard coded the values from domain object here, in my next post i will be making this as dynamic, for time being this is for testing.

/**
 * 
 */
package com.spark.spring.data.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spark.spring.data.domain.PersonDTO;
import com.spark.spring.data.service.PersonService;

/**
 * @author Pavan Kumar Mantha
 *
 */
@Controller
public class ApplicationController {

	@Autowired
	private PersonService personService;
	
	@RequestMapping(value="/create",method=RequestMethod.GET)
	public void create(){
		System.out.println("-------------------inside the method-----------------"+personService);
		PersonDTO personDTO = new PersonDTO();
		personDTO.setFirstName("Pavan Kumar");
		personDTO.setLastName("Mantha");
		personService.create(personDTO);
	}
}

Thats it guys we are done with coding part, now build the project get the war file and deploy it to server.If you see no errors in server console please issue below request from browser “http://localhost:8080/SpringData/rest/create&#8221;.

in server you should see as below.
server_console

and when you query database that should look as below.
database_op

In my next post i will be integrating this project with AngularJs as my front end with fully Ajax driven application.

Happy Coding, Happy Spring Data πŸ™‚

Persisting an Object with EJB3.1

Hello to everyone, in my last post we have seen how to create a stateless session bean and call it from Java Client(Standalone Java code). Today in this post we are going to see how to call Entity Beans from a statefull session bean.

Stateful vs. Stateless Session Beans

A stateful session bean will maintain a conversational state with a client. The state of the session is maintained for the duration of the conversation between the client and the stateful session bean. When the client removes the stateful session bean, its session ends and the state is destroyed. The transient nature of the state of the stateful session bean should not be problematic for either the client or the bean, because once the conversation between the client and the stateful session bean ends, neither the client nor the stateful session bean should have any use for the state.

A stateless session bean will not maintain conversational states for specific clients longer than the period of an individual method invocation. Instance variables used by a method of a stateless bean may have a state, but only for the duration of the method invocation. After a method has finished running either successfully or unsuccessfully, the states of all its instance variables are dropped. The transient nature of this state gives the stateless session bean beneficial attributes, such as the following:

Bean pooling Any stateless session bean method instance that is not currently invoked is equally available to be called by an EJB container or application server to service the request of a client. This allows the EJB container to pool stateless bean instances and increase performance.

Scalability Because stateless session beans are able to service multiple clients, they tend to be more scalable when applications have a large number of clients. When compared to stateful session beans, stateless session beans usually require less instantiation.

Performance An EJB container will never move a stateless session bean from RAM out to a secondary storage, which it may do with a stateful session bean; therefore, stateless session beans may offer greater performance than stateful session beans.

Since no explicit mapping exists between multiple clients and stateless bean instances, the EJB container is free to service any client’s request with any available instance. Even though the client calls the create() and remove() methods of the stateless session bean, making it appear that the client is controlling the lifecycle of an EJB, it is actually the EJB container that is handling the create() and remove() methods without necessarily instantiating or destroying an EJB instance.

Now lets Dive into coding part
project structure looks as below

ProjStruct

in eclipse, create an EJB project, now lets start with our persistence.xml file which will act as communication between code and database. please create a datasource in JBoss AS 7.1 and assign it to persistenceUnit

META-INF/persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
	version="2.0">

	<persistence-unit name="MyPersistenceUnit"
		transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		<jta-data-source>java:/mySqlDS</jta-data-source>
		<class>com.spark.ejb.entites.Employee</class>
		<properties>
			<property name="hibernate.hbm2ddl.auto" value="update" />
			<property name="hibernate.show_sql" value="false" />
			<!-- <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
			<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
			<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test" />
			<property name="hibernate.connection.username" value="root" />
			<property name="hibernate.connection.password" value="root" /> -->

			<property name="hibernate.c3p0.min_size" value="5" />
			<property name="hibernate.c3p0.max_size" value="20" />
			<property name="hibernate.c3p0.timeout" value="300" />
			<property name="hibernate.c3p0.max_statements" value="50" />
			<property name="hibernate.c3p0.idle_test_period" value="3000" />

		</properties>

	</persistence-unit>
</persistence>

Now its time to create EntityManager object which is used to do db manipulations, lets create simple utility class which will return EntityManager object

package com.spark.ejb.persistence.context;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

/**
 * @author Sony
 *
 */
public class PersistenceContextFactory {

	static EntityManager entityManager = Persistence.createEntityManagerFactory("MyPersistenceUnit").createEntityManager();
	
	public static EntityManager getEntityManager(){
		return entityManager; 
	}
}

once we have entityManager Object lets start session beans and its interfaces as below.
EmployeeSessionBeanLocal.java

package com.spark.ejb.session.beans;

import java.util.List;

import javax.ejb.Local;

import com.spark.ejb.entites.Employee;

@Local
public interface EmployeeSessionBeanLocal {

	public void saveObject(Employee employee);
	public <T extends Object> T getObjectById(int id);
	public <T extends Object> List<T> getAllRecords();
}

EmployeeSessionBeanRemote.java

package com.spark.ejb.session.beans;

import java.util.List;

import javax.ejb.Remote;

import com.spark.ejb.entites.Employee;

@Remote
public interface EmployeeSessionBeanRemote {

	public void saveObject(Employee employee);
	public <T extends Object> T getObjectById(int id);
	public <T extends Object> List<T> getAllRecords();
}

EmployeeSessionBean.java

package com.spark.ejb.session.beans;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Remote;
import javax.ejb.Stateful;
import javax.ejb.StatefulTimeout;
import javax.enterprise.context.SessionScoped;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.spark.ejb.entites.Employee;
import com.spark.ejb.persistence.context.PersistenceContextFactory;
import com.spark.ejb.transactions.EmployeeTransactionUnit;

/**
 * Session Bean implementation class EmployeeSessionBean
 */
@Stateful
@SessionScoped
@StatefulTimeout(unit = TimeUnit.MINUTES, value = 10)
@Remote(EmployeeSessionBeanRemote.class)
public class EmployeeSessionBean implements EmployeeSessionBeanRemote, EmployeeSessionBeanLocal {

	EmployeeTransactionUnit employeeTransactionUnit;
	Logger logger = LoggerFactory.getLogger(EmployeeSessionBean.class);
	
	@PostConstruct
	public void afterConstruct(){
		logger.info("--------------------- after construct is called --------------------");
		employeeTransactionUnit = new EmployeeTransactionUnit();
		logger.info("--------------------- employee transaction class instantiated --------------------");
	}
	
	@PostActivate
	public void postActivate(){
		logger.info("--------------------- post activate is called --------------------");
	}
	
    @PreDestroy
    public void preDestroy(){
    	logger.info("---------------- pre destroy called --------------------");
    }
    
    @PrePassivate
    public void prePassivate(){
    	logger.info("---------------- pre passivate called --------------------");
    }

	@Override
	public void saveObject(Employee employee) {
		logger.info("------------------ before calling persist method ---------------------");
		employeeTransactionUnit.persistObject(PersistenceContextFactory.getEntityManager(),employee);
	}
	
	public <T extends Object> T getObjectById(int id){
		return employeeTransactionUnit.getObjectById(PersistenceContextFactory.getEntityManager(), id);
	}
	
	public <T extends Object> List<T> getAllRecords(){
		return employeeTransactionUnit.getAllRecords(PersistenceContextFactory.getEntityManager());
	}

}

at this point lets talk little bit on the above statefull bean, we can specify various life cycle methods using their annotations like (pre passivate,post activate) and we can even specify the bean timeout for the statefull session bean to be in the bean pool, after that it will be passivated and removed from memory by the EJB container.

lets have a look at our entity bean as follows.

/**
 * 
 */
package com.spark.ejb.entites;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 * @author Sony
 * 
 */

@Entity
@Table(name = "employee")
@NamedQueries({
@NamedQuery(name="Employee.getAllRecords",
    query="SELECT e FROM Employee e")          
})
public class Employee implements Serializable,Comparable<Employee> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "EmployeeID")
	private int id;
	
	@Column(name = "FirstName")
	private String firstName;
	@Column(name = "LastName")
	private String lastName;
	@Column(name = "Title")
	private String title;
	@Column(name = "TitleOfCourtesy")
	private String titleOfCourtesy;

	/**
	 * @return the id
	 */
	public int getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	/**
	 * @return the title
	 */
	public String getTitle() {
		return title;
	}

	/**
	 * @param title
	 *            the title to set
	 */
	public void setTitle(String title) {
		this.title = title;
	}

	/**
	 * @return the titleOfCourtesy
	 */
	public String getTitleOfCourtesy() {
		return titleOfCourtesy;
	}

	/**
	 * @param titleOfCourtesy
	 *            the titleOfCourtesy to set
	 */
	public void setTitleOfCourtesy(String titleOfCourtesy) {
		this.titleOfCourtesy = titleOfCourtesy;
	}

	 public int compareTo(Employee obj) {
	        int lastCmp = lastName.compareTo(obj.lastName);
	        return (lastCmp != 0 ? lastCmp : firstName.compareTo(obj.firstName));
	    }
}

In the above entity bean code observe that i have implemented Comparable interface, so that i can have sorting of different records once i retrieve from database.

Now lets see our transaction unit as follows.
note: please observer carefully various generics that i have used to make the code work more generic

/**
 * 
 */
package com.spark.ejb.transactions;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.spark.ejb.entites.Employee;

/**
 * @author Sony
 * 
 */
public class EmployeeTransactionUnit {

	// @PersistenceContext(name="MyPersistenceUnit")
	// EntityManager entityManager;

	Logger logger = LoggerFactory.getLogger(EmployeeTransactionUnit.class);
	
	public <T extends Object> void persistObject(
			EntityManager entityManager, T object) {
		
		EntityTransaction entityTransaction = entityManager.getTransaction();
		try {
			logger.info("------------------ getting transaction object ---------------------");
			entityTransaction.begin();
			logger.info("------------------ using transaction object to persist ---------------------");
			entityManager.persist(object);
			logger.info("------------------ object persisted to database ---------------------");
			entityTransaction.commit();
			logger.info("------------------ transaction committed ---------------------");
		} catch (Exception e) {
			entityTransaction.rollback();
			logger.info("------------------ Exception while transaction ---------------------"+e.getMessage());
		}

	}
	
	@SuppressWarnings("unchecked")
	public <T extends Object> T getObjectById(EntityManager entityManager, int id){
		logger.info("------------------ entity manager to load the object by id ---------------------");
		Employee employee = entityManager.find(Employee.class, id);
		logger.info("------------------ object retrieved ---------------------");
		return (T)employee;
	}
	
	@SuppressWarnings("unchecked")
	public <T extends Object> List<T> getAllRecords(EntityManager entityManager){
		logger.info("------------------ entity manager to load all objects ---------------------");
		Query query = entityManager.createNamedQuery("Employee.getAllRecords");
		List<T> t = query.getResultList();
		logger.info("------------------ list of objects retrieved ---------------------");
		return t;
	}
}



that is it guys our ejb is ready, go head and deploy in JBoss AS 7.1. now its time for us to write a client to test this.

/**
 * 
 */
package com.spark.ejb.client;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * @author Sony
 *
 */
public class ClientUtility {

	private static Context initialContext;
    private static final String PKG_INTERFACE = "org.jboss.ejb.client.naming";
     
    public static Context getInitialContext() throws NamingException{
        if(initialContext == null){
            Properties properties = new Properties();
            properties.put(Context.URL_PKG_PREFIXES, PKG_INTERFACE);
             
            initialContext = new InitialContext(properties);
        }
        return initialContext;
    }
}

/**
 * 
 */
package com.spark.ejb.client;

import java.util.Collections;
import java.util.List;

import javax.naming.Context;
import javax.naming.NamingException;

import com.spark.ejb.entites.Employee;
import com.spark.ejb.session.beans.EmployeeSessionBean;
import com.spark.ejb.session.beans.EmployeeSessionBeanRemote;

/**
 * @author Sony
 * 
 */
public class EJBClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		EmployeeSessionBeanRemote bean = doLookUp();
		
		Employee employee = new Employee();
		employee.setFirstName("Venkata Subramanya Deepak");
		employee.setLastName("Mantha");
		employee.setTitle("Scientific Office D");
		employee.setTitleOfCourtesy("Mr");
		
		//bean.saveObject(employee);
		Employee employee2 = bean.getObjectById(11);
		System.out.println(employee2.getTitleOfCourtesy()+" "+employee2.getFirstName()+" "+employee2.getLastName());
		
		List<Employee> list = bean.getAllRecords();
		Collections.sort(list);
		
		for(Employee employee3 : list){
			System.out.println(employee3.getLastName()+" "+employee3.getFirstName());
		}
		
	}

	private static EmployeeSessionBeanRemote doLookUp() {
		Context context = null;
		EmployeeSessionBeanRemote bean = null;
		try {
			// 1. Obtaining Context
			context = ClientUtility.getInitialContext();
			// 2. Generate JNDI Lookup name
			String lookupName = getLookUpName();
			// 3. Lookup and cast
			bean = (EmployeeSessionBeanRemote) context.lookup(lookupName);

		} catch (NamingException e) {
			e.printStackTrace();
		}
		return bean;
	}

	private static String getLookUpName() {

		// AppName is the .ear file name without extension, if no .ear is
		// deployed then this is empty
		String appName = "";

		// module name is the EJB jar file deployed without .jar extension
		String moduleName = "EJBCRUDProject";

		String distinctName = "";

		// EJB bean impl class name
		String beanName = EmployeeSessionBean.class.getSimpleName();

		// Fully qualified remoteInterface Name
		String interfaceName = EmployeeSessionBeanRemote.class.getName();

		// Create a look up string name
		String name = "ejb:" + appName + "/" + moduleName + "/" + distinctName
				+ "/" + beanName + "!" + interfaceName+"?stateful";

		return name;
	}
}

once you run the client you should be able to see similar kind of output on the server console.

output

note: i did not code the update logic its left for you people to do it.

Happy Session Beans and Entity Beans πŸ™‚ Happy EJB πŸ™‚

ExtJS With Spring MVC

Hi all its been long days i put a post on my blog. most of my colleagues were requesting me to put a write up on EXTJS and integrating it with Spring3.x MVC so here is my write for all those who were waiting for it. Basically EXTJS is Extended java script and every widget that you see on the page are coded as components and lot of features included in it. ExtJS comes in two flavors licensed and Open source. you can download ExtJS Lib from Sencha site.

the below is the java project struct for your reference
proj_struct

and here is the web project structure(Webcontent)
proj_struct2

Now lets start creating the UI. the main container which holds most of the components in the extjs page is called ViewPost and here is the code for that

Ext.require([ '*' ]);

Ext.onReady(function() {

	Ext.QuickTips.init();

	//Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));
	var panel;
	var viewport = Ext.create('Ext.Viewport', {
		id : 'border-example',
		layout : 'border',
		items : [

		Ext.create('Ext.Component', {
			region : 'north',
			height : 0

		}),

		{
			xtype : 'tabpanel',
			region : 'east',
			title : 'Help Menu',
			dockedItems : [ {
				dock : 'top',
				xtype : 'toolbar',
				items : [ '->', {
					xtype : 'button',
					text : 'test',
					tooltip : 'Test Button'
				} ]
			} ],
			animCollapse : true,
			collapsible : true,
			split : true,
			width : 225,
			minSize : 175,
			maxSize : 400,
			margins : '0 5 0 0',
			activeTab : 1,
			tabPosition : 'bottom',
			items : []
		}, {
			region : 'west',
			stateId : 'navigation-panel',
			id : 'west-panel',
			title : 'Navigation Menu',
			split : true,
			width : 200,
			minWidth : 175,
			maxWidth : 400,
			collapsible : true,
			animCollapse : true,
			margins : '0 0 0 5',
			layout : 'accordion',
			items : [ {
				contentEl : 'west',
				title : '<b>Inventory</b>',
				iconCls : 'nav'
			}, {
				title : 'Purchase Order',
				iconCls : 'settings'
			}, {
				title : 'Patient Management',
				iconCls : 'info'
			} ]
		},

		panel = Ext.create('Ext.tab.Panel', {
			region : 'center',
			deferredRender : false,
			activeTab : 0
		}) ]
	});
	Ext.select("a.newProduct").on('click', function() {
		var tabExists = false;
		var items = panel.items.items;
		for ( var i = 0; i < items.length; i++) {
			if (items[i].id === 'NewProduct') {
				panel.setActiveTab(i);
				tabExists = true;
				panel.setActiveTab(i);
			}
		}
		if (!tabExists) {
			panel.insert(1, NewProduct);
			panel.setActiveTab(0);
		}
	});
	
	Ext.select("a.newFrame").on('click', function() {
		var tabExists = false;
		var items = panel.items.items;
		for ( var i = 0; i < items.length; i++) {
			if (items[i].id === 'NewFrame') {
				panel.setActiveTab(i);
				tabExists = true;
				panel.setActiveTab(i);
			}
		}
		if (!tabExists) {
			panel.insert(1, NewFrame);
			panel.setActiveTab(0);
		}
	});
	
	Ext.select("a.searchProd").on('click', function() {
		var tabExists = false;
		var items = panel.items.items;
		for ( var i = 0; i < items.length; i++) {
			if (items[i].id === 'searchFrame') {
				panel.setActiveTab(i);
				tabExists = true;
				panel.setActiveTab(i);
			}
		}
		if (!tabExists) {
			panel.insert(1, SearchFrame);
			panel.setActiveTab(0);
		}
	});
	
	Ext.select("a.newContactLens").on('click', function() {
		var tabExists = false;
		var items = panel.items.items;
		if(items.length > 0){
			for(var i = 0 ; i < items.length; i++){
				if(items[i].id === 'newContactLens'){
					panel.setActiveTab(i);
					tabExists = true;
					panel.setActiveTab(i);
				}
			}
		}
		if(!tabExists){
			panel.insert(1,newContactLens);
			panel.setActiveTab(0);
		}
	});
});

below is the code for creating a tabbed panel which is inside the ViewPort and all the form components are in the TabbedPanel. this can be done as below.

var item_type_store = Ext.create('Ext.data.Store', {
	fields : [ 'text' ],
	data : [ {
		text : 'type_1'
	}, {
		text : 'type_2'
	}, {
		text : 'type_3'
	}, {
		text : 'type_4'
	}, {
		text : 'type_5'
	}, {
		text : 'type_6'
	} ]
});

var item_type = Ext.create('Ext.form.field.ComboBox', {
	store : item_type_store,
	fieldLabel : 'ItemType',
	name : 'itemtype',
	xtype: 'tbfill'
});

var item_location_store = Ext.create('Ext.data.Store', {
	fields : [ 'text' ],
	data : [ {
		text : 'location_1'
	}, {
		text : 'location_2'
	}, {
		text : 'location_3'
	}, {
		text : 'location_4'
	}, {
		text : 'location_5'
	}, {
		text : 'location_6'
	}, {
		text : 'location_7'
	} ]
});

var item_location = Ext.create('Ext.form.field.ComboBox', {
	store : item_location_store,
	fieldLabel : 'ItemLocation',
	name : 'itemLocation'
});

var supplier_name_store = Ext.create('Ext.data.Store', {
	fields : [ 'text' ],
	data : [ {
		text : 'supplier_1'
	}, {
		text : 'supplier_2'
	}, {
		text : 'supplier_3'
	}, {
		text : 'supplier_4'
	}, {
		text : 'supplier_5'
	}, {
		text : 'supplier_6'
	}, {
		text : 'supplier_7'
	} ]
});

var supplier_name = Ext.create('Ext.form.field.ComboBox', {
	store : supplier_name_store,
	fieldLabel : 'SupplierName',
	name : 'supplierName'
});

var brand_collection_store = Ext.create('Ext.data.Store', {
	fields : [ 'text' ],
	data : [ {
		text : 'Brand_1'
	}, {
		text : 'Brand_2'
	}, {
		text : 'Brand_3'
	}, {
		text : 'Brand_4'
	}, {
		text : 'Brand_5'
	}, {
		text : 'Brand_6'
	}, {
		text : 'Brand_7'
	}, {
		text : 'Brand_8'
	} ]
});

var brand_collection = Ext.create('Ext.form.field.ComboBox', {
	store : brand_collection_store,
	fieldLabel : 'Brand/Collection',
	name : 'brandCollection'
});

var NewProduct = Ext.create('Ext.form.Panel', {
	layout : 'vbox',
	contentEl : 'center2',
	title : 'New Product',
	id : 'NewProduct',
	defaults : {
		bodyPadding : 10

	},
	items : [ {
		xtype : 'panel',
		width : 900,
		collapsible: true,
		title : 'Product Details',
		defaults : {
			width : 230,
			cls : 'form-field'
		},
		defaultType : 'textfield',
		items : [ {
			fieldLabel : 'SrNo',
			name : 'srNo',
			value : '',
			validator : function(event) {
				if (!(/[0-9]/.test(this.getValue()))) {
					return "This Field should be in Numbers only";
				}
				return true;
			}
		}, {
			fieldLabel : 'ItemNumber',
			name : 'iteNumber',
			value : ''
		
		}, {
			fieldLabel : 'Description',
			name : 'desc',
			value : ''
		
		}, {
			fieldLabel : 'Item Code',
			name : 'itemCode',
			value : ''
		
		}, {
			xtype : item_type,
			labelClsExtra : 'form-field'
		}, {
			xtype : item_location,
			labelClsExtra : 'form-field'
		}, {
			xtype : supplier_name,
			labelClsExtra : 'form-field'
		}, {
			xtype : brand_collection,
			labelClsExtra : 'form-field'
		}, {
			fieldLabel : 'Tax(%)',
			name : 'itemTax',
			value : ''
		
		}]
	}, {
		xtype : 'panel',
		title : 'Product Attributes',
		width : 900,
		flex : 2,
		collapsible: true,
		defaults : {
			cls : 'form-field'
		},
		items : [ {
			xtype : 'checkbox',
			fieldLabel : 'Active',
			name : 'active',
			checked : false,
		}, {
			xtype : 'checkbox',
			fieldLabel : 'Discounted',
			name : 'discounted',
			checked : false,
		}, {
			xtype : 'checkbox',
			fieldLabel : 'Dispensable',
			name : 'dispensable',
			checked : false,
		}, {
			xtype : 'checkbox',
			fieldLabel : 'Taxable',
			name : 'taxable',
			checked : false,
		} ]
	},{
		xtype : 'panel',
		title : 'Product Cost Details',
		width : 900,
		flex : 2,
		collapsible: true,
		autoScroll: true,
		defaults : {
			cls : 'form-field'
		},
		items : [ {
			xtype : 'textfield',
			fieldLabel : 'SupplierCost',
			name : 'supplierCost',
			value : ''
		
		}, {
			xtype : 'textfield',
			fieldLabel : 'LandingCost',
			name : 'landingCost',
			value : ''
		
		}, {
			xtype : 'textfield',
			fieldLabel : 'LastOrdered',
			name : 'lastOrdered',
			value : ''
		}, {
			xtype : 'textfield',
			fieldLabel : 'LastReceived',
			name : 'lastReceived',
			value : ''
		},  {
			xtype : 'textfield',
			fieldLabel : 'QuantityOrdered',
			name : 'quantityOnOrder',
			value : ''
		
		}, {
			xtype : 'textfield',
			fieldLabel : 'QuantityReceived',
			name : 'quantityReceived',
			value : ''
		
		}]
	} ],
	buttons : [
			{
				text : 'Save',
				handler : function() {
					var productForm = this.up('form').getForm();
					if (!productForm.isValid()) {
						alert("Please enter proper details!");
					} else {
						console.log(productForm.getValues());
						Ext.Ajax.request({
							url : 'spring/product/newproduct',
							method : 'POST',
							params : {
								productDetails : Ext
										.encode(productForm.getValues())
							},
							scope : this,
							success : function(response) {
								// Received response from the server
								msg = Ext.decode(response.responseText);
								if (msg.success) {
									Ext.MessageBox.alert('',
											msg.message);
								} else {
									Ext.MessageBox.alert('',
											msg.message);
								}
							},
							failure : function(response) {
								Ext.MessageBox.alert(msg.message);
							}
						});
					}

				}
			}, {
				text : 'Cancel',
				handler : function() {
					this.up('form').getForm().reset();
				}
			} ]

});

the above code has lot many things to understand. There are data stores that got created, components such textfields, comboboxt etc , buttons and their handlers. inside the handlers we have Ajax calls that will submit the form data to our spring controller.

the main moto of ExtJs is one HTML and many JavaScript files now to launch our application we need one initial page that launches and renders the extjs components and here it goes

<html>
<head>
<title>Vision One</title>

<link rel="stylesheet" type="text/css"
	href="resources/extjs/resources/css/ext-all.css">
<link rel="stylesheet" type="text/css"
	href="resources/extjs/resources/css/vision-one-custom.css">
<script type="text/javascript" src="resources/extjs/ext-all-debug.js"></script>
<script type="text/javascript" src="view/newProduct.js"></script>
<script type="text/javascript" src="view/newContactLens.js"></script>
<script type="text/javascript" src="view/newFrame.js"></script>
<script type="text/javascript" src="view/searchProduct.js"></script>
<script type="text/javascript" src="view/vision_ui.js"></script>

</head>
<body>
	<!-- use class="x-hide-display" to prevent a brief flicker of the content -->
	<div id="west" class="x-hide-display">
		<ul>
			<li><a href="#" class="newProduct">New Product(others)</a></li>
			<li><a href="#" class="newFrame">New Frames</a></li>
			<li><a href="#" class="newContactLens">New Contact Lens</a></li>
			<li><a href="#" class="searchProd">Search Products</a></li>
			<li><a href="#" class="searchFrame">Search Frames</a></li>
			<li><a href="#" class="searchLense">Search Lenses</a></li>
		</ul>
	</div>
	<div id="center2" class="x-hide-display"></div>
	<div id="center1" class="x-hide-display"></div>
	<div id="props-panel" class="x-hide-display"
		style="width: 200px; height: 200px; overflow: hidden;"></div>
</body>
</html>

Now lets look at the Middleware where the technology used is Spring MVC. First the request from ExtJS hits one of our spring REST based controller from there the request is deligated to service layer(Service IMPL) and from there again the request is deligated to DAO layer(DAO IMPL). lets look into our spring REST controller implementation

package com.spark.visionone.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;
import com.spark.visionone.service.ProductService;
import com.spark.visionone.utils.VisionOneUtils;

/**
 * @author Pavan Kumar Mantha
 *
 */
@Controller
@RequestMapping(value="/product")
public class ProductController {
	
	@Autowired
	ProductService productService;
	
	@RequestMapping(value="/newproduct",method =RequestMethod.POST)
	public @ResponseBody String saveProductDetails(HttpServletRequest httpServletRequest){
		
		String jsonStr = httpServletRequest.getParameter("productDetails");
		System.out.println(jsonStr);
		OtherProduct otherProduct = VisionOneUtils.JsonToJava(jsonStr, OtherProduct.class);
		GenericMessageObject genericMessageObject = productService.saveProductDetails(otherProduct);
		String jsonResonseStr = VisionOneUtils.JavaToJson(genericMessageObject);
		return jsonResonseStr;
	}
	
}

In the above implementation if you observer the method is annotaed as “@ResponseBody” which will help spring controller to return JSON object back to the ExtJS.

Now its time to see our Service Layer.

package com.spark.visionone.service;

import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;

/**
 * @author Pavan kumar made class to return
 *         GenericMessageObject and passing OtherProduct object as parameter
 */
public interface ProductService {

	public GenericMessageObject saveProductDetails(OtherProduct otherProduct);

}

Now lets see the implementation of the service interface that we have created.

/**
 * 
 */
package com.spark.visionone.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spark.visionone.dao.ProductDAO;
import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;
import com.spark.visionone.service.ProductService;

/**
 * @author Pavan Kumar Mantha
 *
 */
@Service(value="productService")
public class ProductServiceImpl implements ProductService{

	@Autowired
	ProductDAO productDAO;
	
	@Override
	public GenericMessageObject saveProductDetails(OtherProduct otherProduct) {
		return productDAO.saveProduct(otherProduct);
	}

}

Now lets us look into the interface and its implementation of DAO Layer at once.

/**
 * 
 */
package com.spark.visionone.dao;

import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;

/**
 * @author PavanKumar Mantha
 *
 */
public interface ProductDAO {

	public GenericMessageObject saveProduct(OtherProduct otherProduct);
}

/**
 * 
 */
package com.spark.visionone.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.spark.visionone.dao.ProductDAO;
import com.spark.visionone.model.GenericMessageObject;
import com.spark.visionone.model.NewFrame;
import com.spark.visionone.model.OtherProduct;

/**
 * @author PavanKumar Mantha
 *
 */
@Repository(value="productDAO")
public class ProductDAOImpl implements ProductDAO {

	@PersistenceContext
	EntityManager entityManager;
	/* (non-Javadoc)
	 * @see com.spark.visionone.dao.ProductDAO#saveProduct(com.spark.visionone.model.OtherProduct)
	 */
	@Override
	public GenericMessageObject saveProduct(OtherProduct otherProduct) {
		GenericMessageObject genericMessageObject = new GenericMessageObject();
		try {
			
			/*
			 *  logic to persist
			 *  entityManager.persist(otherProduct);
			 */
			entityManager.persist(otherProduct);
			System.out.println("Other Product: "+otherProduct.getBrandCollection());
			genericMessageObject.setSuccess(true);
			genericMessageObject.setMessage("details saved successfully !");
		} catch (Exception e) {
			e.printStackTrace();
			genericMessageObject.setSuccess(false);
			genericMessageObject.setMessage("Exception in saving details !");
		}
		return genericMessageObject;
	}
	
	
}

Here we used JPA to persist the objects to back end database.
the below are the different Model (pojo) classes that are used in the project for data storage and communication between different layers.

BaseVO.java

/**
 * 
 */
package com.spark.visionone.model;

import java.io.Serializable;
import java.sql.Date;

import javax.persistence.Column;

/**
 * @author PavanKumar Mantha
 * 
 */
public class BaseVO implements Serializable {

	private Date createdDate;
	private Date updateDate;

	/**
	 * @return the createdDate
	 */
	@Column
	public Date getCreatedDate() {
		return createdDate;
	}

	/**
	 * @param createdDate
	 *            the createdDate to set
	 */
	public void setCreatedDate(Date createdDate) {
		this.createdDate = createdDate;
	}

	/**
	 * @return the updateDate
	 */
	@Column
	public Date getUpdateDate() {
		return updateDate;
	}

	/**
	 * @param updateDate
	 *            the updateDate to set
	 */
	public void setUpdateDate(Date updateDate) {
		this.updateDate = updateDate;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((createdDate == null) ? 0 : createdDate.hashCode());
		result = prime * result
				+ ((updateDate == null) ? 0 : updateDate.hashCode());
		return result;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof BaseVO)) {
			return false;
		}
		BaseVO other = (BaseVO) obj;
		if (createdDate == null) {
			if (other.createdDate != null) {
				return false;
			}
		} else if (!createdDate.equals(other.createdDate)) {
			return false;
		}
		if (updateDate == null) {
			if (other.updateDate != null) {
				return false;
			}
		} else if (!updateDate.equals(other.updateDate)) {
			return false;
		}
		return true;
	}

}

OtherProduct.java

/**
 * 
 */
package com.spark.visionone.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * @author PavanKumar Mantha
 * 
 */
@Entity
@Table(name="new_product")
public class OtherProduct extends BaseVO implements Serializable {

	private String srNo;
	private String iteNumber;
	private String desc;
	private String itemCode;
	private String itemtype;
	private String ItemLocation;
	private String supplierName;
	private String brandCollection;
	private String active;
	private String discounted;
	private String dispensable;
	private String taxable;
	private String supplierCost;
	private String landingCost;
	private String lastOrdered;
	private String lastReceived;
	private String lastSold;
	private String quantityOnOrder;
	private String quantityOnHand;
	private String totalSold;
	private String quantityReceived;

	/**
	 * @return the srNo
	 */
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="SrNo")
	public String getSrNo() {
		return srNo;
	}

	/**
	 * @param srNo
	 *            the srNo to set
	 */
	public void setSrNo(String srNo) {
		this.srNo = srNo;
	}

	/**
	 * @return the iteNumber
	 */
	@Column
	public String getIteNumber() {
		return iteNumber;
	}

	/**
	 * @param iteNumber
	 *            the iteNumber to set
	 */
	public void setIteNumber(String iteNumber) {
		this.iteNumber = iteNumber;
	}

	/**
	 * @return the desc
	 */
	@Column
	public String getDesc() {
		return desc;
	}

	/**
	 * @param desc
	 *            the desc to set
	 */
	public void setDesc(String desc) {
		this.desc = desc;
	}

	/**
	 * @return the itemCode
	 */
	@Column
	public String getItemCode() {
		return itemCode;
	}

	/**
	 * @param itemCode
	 *            the itemCode to set
	 */
	public void setItemCode(String itemCode) {
		this.itemCode = itemCode;
	}

	/**
	 * @return the itemtype
	 */
	@Column
	public String getItemtype() {
		return itemtype;
	}

	/**
	 * @param itemtype
	 *            the itemtype to set
	 */
	public void setItemtype(String itemtype) {
		this.itemtype = itemtype;
	}

	/**
	 * @return the itemLocation
	 */
	@Column
	public String getItemLocation() {
		return ItemLocation;
	}

	/**
	 * @param itemLocation
	 *            the itemLocation to set
	 */
	public void setItemLocation(String itemLocation) {
		ItemLocation = itemLocation;
	}

	/**
	 * @return the supplierName
	 */
	@Column
	public String getSupplierName() {
		return supplierName;
	}

	/**
	 * @param supplierName
	 *            the supplierName to set
	 */
	public void setSupplierName(String supplierName) {
		this.supplierName = supplierName;
	}

	/**
	 * @return the brandCollection
	 */
	@Column
	public String getBrandCollection() {
		return brandCollection;
	}

	/**
	 * @param brandCollection
	 *            the brandCollection to set
	 */
	public void setBrandCollection(String brandCollection) {
		this.brandCollection = brandCollection;
	}

	/**
	 * @return the active
	 */
	@Column
	public String getActive() {
		return active;
	}

	/**
	 * @param active
	 *            the active to set
	 */
	public void setActive(String active) {
		this.active = active;
	}

	/**
	 * @return the discounted
	 */
	@Column
	public String getDiscounted() {
		return discounted;
	}

	/**
	 * @param discounted
	 *            the discounted to set
	 */
	public void setDiscounted(String discounted) {
		this.discounted = discounted;
	}

	/**
	 * @return the dispensable
	 */
	@Column
	public String getDispensable() {
		return dispensable;
	}

	/**
	 * @param dispensable
	 *            the dispensable to set
	 */
	public void setDispensable(String dispensable) {
		this.dispensable = dispensable;
	}

	/**
	 * @return the taxable
	 */
	@Column
	public String getTaxable() {
		return taxable;
	}

	/**
	 * @param taxable
	 *            the taxable to set
	 */
	public void setTaxable(String taxable) {
		this.taxable = taxable;
	}

	/**
	 * @return the supplierCost
	 */
	@Column
	public String getSupplierCost() {
		return supplierCost;
	}

	/**
	 * @param supplierCost
	 *            the supplierCost to set
	 */
	public void setSupplierCost(String supplierCost) {
		this.supplierCost = supplierCost;
	}

	/**
	 * @return the landingCost
	 */
	@Column
	public String getLandingCost() {
		return landingCost;
	}

	/**
	 * @param landingCost
	 *            the landingCost to set
	 */
	public void setLandingCost(String landingCost) {
		this.landingCost = landingCost;
	}

	/**
	 * @return the lastOrdered
	 */
	@Column
	public String getLastOrdered() {
		return lastOrdered;
	}

	/**
	 * @param lastOrdered
	 *            the lastOrdered to set
	 */
	public void setLastOrdered(String lastOrdered) {
		this.lastOrdered = lastOrdered;
	}

	/**
	 * @return the lastReceived
	 */
	@Column
	public String getLastReceived() {
		return lastReceived;
	}

	/**
	 * @param lastReceived
	 *            the lastReceived to set
	 */
	public void setLastReceived(String lastReceived) {
		this.lastReceived = lastReceived;
	}

	/**
	 * @return the lastSold
	 */
	@Column
	public String getLastSold() {
		return lastSold;
	}

	/**
	 * @param lastSold
	 *            the lastSold to set
	 */
	public void setLastSold(String lastSold) {
		this.lastSold = lastSold;
	}

	/**
	 * @return the quantityOnOrder
	 */
	@Column
	public String getQuantityOnOrder() {
		return quantityOnOrder;
	}

	/**
	 * @param quantityOnOrder
	 *            the quantityOnOrder to set
	 */
	public void setQuantityOnOrder(String quantityOnOrder) {
		this.quantityOnOrder = quantityOnOrder;
	}

	/**
	 * @return the quantityOnHand
	 */
	@Column
	public String getQuantityOnHand() {
		return quantityOnHand;
	}

	/**
	 * @param quantityOnHand
	 *            the quantityOnHand to set
	 */
	public void setQuantityOnHand(String quantityOnHand) {
		this.quantityOnHand = quantityOnHand;
	}

	/**
	 * @return the totalSold
	 */
	@Column
	public String getTotalSold() {
		return totalSold;
	}

	/**
	 * @param totalSold
	 *            the totalSold to set
	 */
	public void setTotalSold(String totalSold) {
		this.totalSold = totalSold;
	}
	
	/**
	 * @return the quantityReceived
	 */
	@Column
	public String getQuantityReceived() {
		return quantityReceived;
	}

	/**
	 * @param quantityReceived the quantityReceived to set
	 */
	public void setQuantityReceived(String quantityReceived) {
		this.quantityReceived = quantityReceived;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((ItemLocation == null) ? 0 : ItemLocation.hashCode());
		result = prime * result + ((active == null) ? 0 : active.hashCode());
		result = prime * result
				+ ((brandCollection == null) ? 0 : brandCollection.hashCode());
		result = prime * result + ((desc == null) ? 0 : desc.hashCode());
		result = prime * result
				+ ((discounted == null) ? 0 : discounted.hashCode());
		result = prime * result
				+ ((dispensable == null) ? 0 : dispensable.hashCode());
		result = prime * result
				+ ((iteNumber == null) ? 0 : iteNumber.hashCode());
		result = prime * result
				+ ((itemCode == null) ? 0 : itemCode.hashCode());
		result = prime * result
				+ ((itemtype == null) ? 0 : itemtype.hashCode());
		result = prime * result
				+ ((landingCost == null) ? 0 : landingCost.hashCode());
		result = prime * result
				+ ((lastOrdered == null) ? 0 : lastOrdered.hashCode());
		result = prime * result
				+ ((lastReceived == null) ? 0 : lastReceived.hashCode());
		result = prime * result
				+ ((lastSold == null) ? 0 : lastSold.hashCode());
		result = prime * result
				+ ((quantityOnHand == null) ? 0 : quantityOnHand.hashCode());
		result = prime * result
				+ ((quantityOnOrder == null) ? 0 : quantityOnOrder.hashCode());
		result = prime * result + ((srNo == null) ? 0 : srNo.hashCode());
		result = prime * result
				+ ((supplierCost == null) ? 0 : supplierCost.hashCode());
		result = prime * result
				+ ((supplierName == null) ? 0 : supplierName.hashCode());
		result = prime * result + ((taxable == null) ? 0 : taxable.hashCode());
		result = prime * result
				+ ((totalSold == null) ? 0 : totalSold.hashCode());
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof OtherProduct)) {
			return false;
		}
		OtherProduct other = (OtherProduct) obj;
		if (ItemLocation == null) {
			if (other.ItemLocation != null) {
				return false;
			}
		} else if (!ItemLocation.equals(other.ItemLocation)) {
			return false;
		}
		if (active == null) {
			if (other.active != null) {
				return false;
			}
		} else if (!active.equals(other.active)) {
			return false;
		}
		if (brandCollection == null) {
			if (other.brandCollection != null) {
				return false;
			}
		} else if (!brandCollection.equals(other.brandCollection)) {
			return false;
		}
		if (desc == null) {
			if (other.desc != null) {
				return false;
			}
		} else if (!desc.equals(other.desc)) {
			return false;
		}
		if (discounted == null) {
			if (other.discounted != null) {
				return false;
			}
		} else if (!discounted.equals(other.discounted)) {
			return false;
		}
		if (dispensable == null) {
			if (other.dispensable != null) {
				return false;
			}
		} else if (!dispensable.equals(other.dispensable)) {
			return false;
		}
		if (iteNumber == null) {
			if (other.iteNumber != null) {
				return false;
			}
		} else if (!iteNumber.equals(other.iteNumber)) {
			return false;
		}
		if (itemCode == null) {
			if (other.itemCode != null) {
				return false;
			}
		} else if (!itemCode.equals(other.itemCode)) {
			return false;
		}
		if (itemtype == null) {
			if (other.itemtype != null) {
				return false;
			}
		} else if (!itemtype.equals(other.itemtype)) {
			return false;
		}
		if (landingCost == null) {
			if (other.landingCost != null) {
				return false;
			}
		} else if (!landingCost.equals(other.landingCost)) {
			return false;
		}
		if (lastOrdered == null) {
			if (other.lastOrdered != null) {
				return false;
			}
		} else if (!lastOrdered.equals(other.lastOrdered)) {
			return false;
		}
		if (lastReceived == null) {
			if (other.lastReceived != null) {
				return false;
			}
		} else if (!lastReceived.equals(other.lastReceived)) {
			return false;
		}
		if (lastSold == null) {
			if (other.lastSold != null) {
				return false;
			}
		} else if (!lastSold.equals(other.lastSold)) {
			return false;
		}
		if (quantityOnHand == null) {
			if (other.quantityOnHand != null) {
				return false;
			}
		} else if (!quantityOnHand.equals(other.quantityOnHand)) {
			return false;
		}
		if (quantityOnOrder == null) {
			if (other.quantityOnOrder != null) {
				return false;
			}
		} else if (!quantityOnOrder.equals(other.quantityOnOrder)) {
			return false;
		}
		if (srNo == null) {
			if (other.srNo != null) {
				return false;
			}
		} else if (!srNo.equals(other.srNo)) {
			return false;
		}
		if (supplierCost == null) {
			if (other.supplierCost != null) {
				return false;
			}
		} else if (!supplierCost.equals(other.supplierCost)) {
			return false;
		}
		if (supplierName == null) {
			if (other.supplierName != null) {
				return false;
			}
		} else if (!supplierName.equals(other.supplierName)) {
			return false;
		}
		if (taxable == null) {
			if (other.taxable != null) {
				return false;
			}
		} else if (!taxable.equals(other.taxable)) {
			return false;
		}
		if (totalSold == null) {
			if (other.totalSold != null) {
				return false;
			}
		} else if (!totalSold.equals(other.totalSold)) {
			return false;
		}
		return true;
	}
}

GenericMessageObject.java

/**
 * 
 */
package com.spark.visionone.model;

import java.io.Serializable;

/**
 * @author PavanKumar Mantha
 * 
 */
public class GenericMessageObject implements Serializable{

	private Boolean success;
	private String message;

	/**
	 * @return the success
	 */
	public Boolean getSuccess() {
		return success;
	}

	/**
	 * @param success
	 *            the success to set
	 */
	public void setSuccess(Boolean success) {
		this.success = success;
	}

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message
	 *            the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}

}

Here are the configuration files required for Spring and JPA to run un combination.
WEB-INF/spring/application-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

	<!-- Activates various annotations to be detected in bean classes for ex @Autowired -->
	<context:annotation-config/>
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<context:component-scan base-package="com.spark.visionone"/>
	
	<tx:annotation-driven/>
	
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="persistentUnit"/>
		<property name="dataSource" ref="dataSource"/>
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="showSql" value="true"/>
				<property name="generateDdl" value="false"/>
				<property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
			</bean>
		</property>
	</bean>
	
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/visionone"/>
		<property name="username" value="root"/>
		<property name="password" value="root"/>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory"/>
	</bean>
</beans>

WEB-INF/spring/spring-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<context:annotation-config/>
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<context:component-scan base-package="com.spark.visionone"/>
	
	<tx:annotation-driven/>
	
	
	<!-- <mvc:resources location="/extjs/**" mapping="/resources/extjs"/> -->
</beans:beans>

WEB-INF/classes/META-INF/persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
	version="2.0">
	
	<persistence-unit name="persistentUnit" transaction-type="RESOURCE_LOCAL">
	<class>com.spark.visionone.model.OtherProduct</class>
	<class>com.spark.visionone.model.BaseVO</class>
	<class>com.spark.visionone.model.GenericMessageObject</class>
	</persistence-unit>
	
</persistence>

The project depending libs are as follows:
project-libs

this completes the coding part and its time for deployment and running the project. we can deploy the project to any web container and ran and say submit once all the fields ad filled you can see the request to spring controller is fired as below and data is sent in JSON format

finally the screen looks like this:
finalScreen

request

Dedicated to all those who want to learn EXTJS
Happy Coding πŸ™‚

How to create dynamic UI with database config

Hi all here is a small post how to make your user interface(html) dynamically. In the sense just change your database and your user interface changes. the technologies used here are Spring3.x, hibernate3.x and Freemarker
and the specialty here is there is not even a single xml configuration involved.

below are the classes for the spring configuration.

/**
 * 
 */
package com.spark.spring.config;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

/**
 * @author PavanKumar Mantha
 *
 */
@Configuration
@EnableTransactionManagement
@EnableWebMvc
@Import({})
@ComponentScan(basePackages="com.spark.spring")
public class WebApplicationConfig extends WebMvcConfigurerAdapter{

	@Bean
	public FreeMarkerViewResolver getFreeMarkerViewResolver(){
		FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
		freeMarkerViewResolver.setPrefix("");
		freeMarkerViewResolver.setSuffix(".ftl");
		
		return freeMarkerViewResolver;
	}
	
	@Bean
	public FreeMarkerConfigurer getFreeMarkerConfigurer(){
		FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
		freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/ftl/");
		return freeMarkerConfigurer;
	}
	
	/*@Bean
	public InternalResourceViewResolver getInternalResourceViewResolver(){
	
		InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
		internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
		internalResourceViewResolver.setSuffix(".jsp");
		
		return internalResourceViewResolver;
	}*/
	
	@Bean
	public PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer(){
		
		PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer();
		placeholderConfigurer.setLocation(new ClassPathResource("application.properties"));
		placeholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
		return placeholderConfigurer;
	}
	
	public void addResourceHandler(ResourceHandlerRegistry resourceHandlerRegistry){
		resourceHandlerRegistry.addResourceHandler("/resources/**").addResourceLocations("/resources");
	}
}

/**
 * 
 */
package com.spark.spring.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * @author PavanKumar Mantha
 *
 */
public class WebAppInitializer implements WebApplicationInitializer{

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
		annotationConfigWebApplicationContext.register(WebApplicationConfig.class);
		annotationConfigWebApplicationContext.setServletContext(servletContext);
		
		Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(annotationConfigWebApplicationContext));
		dynamic.addMapping("/");
		dynamic.setLoadOnStartup(1);
	}

}

/**
 * 
 */
package com.spark.spring.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.HibernateTransactionManager;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

/**
 * @author PavanKumar Mantha
 * 
 */
@Configuration
public class HibernateConfiguration {

	@Value("${database.driver}")
	private String driverClassName;
	@Value("${database.url}")
	private String url;
	@Value("${database.user}")
	private String username;
	@Value("${database.password}")
	private String password;

	@Value("${hibernate.dialect}")
	private String hibernateDialect;
	@Value("${hibernate.show_sql}")
	private String hibernateShowSql;
	@Value("${hibernate.hbm2ddl.auto}")
	private String hibernateHbm2ddlAuto;

	@Bean
	public DataSource getDataSource() {

		DriverManagerDataSource dataSource = new DriverManagerDataSource();
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);

		return dataSource;
	}

	@Bean
	public AnnotationSessionFactoryBean getAnnotationSessionFactoryBean() {
		AnnotationSessionFactoryBean annotationSessionFactoryBean = new AnnotationSessionFactoryBean();
		annotationSessionFactoryBean.setDataSource(getDataSource());
		annotationSessionFactoryBean
				.setHibernateProperties(getHibernateProperties());
		annotationSessionFactoryBean
				.setPackagesToScan(new String[] { "com.spark.spring" });
		return annotationSessionFactoryBean;
	}

	@Bean
	@Autowired
	public HibernateTransactionManager transactionManager(
			SessionFactory sessionFactory) {
		HibernateTransactionManager htm = new HibernateTransactionManager();
		htm.setSessionFactory(sessionFactory);
		return htm;
	}

	@Bean
	@Autowired
	public HibernateTemplate getHibernateTemplate(SessionFactory sessionFactory) {
		HibernateTemplate hibernateTemplate = new HibernateTemplate(
				sessionFactory);
		return hibernateTemplate;
	}

	@Bean
	public Properties getHibernateProperties() {
		Properties properties = new Properties();
		properties.put("hibernate.dialect", hibernateDialect);
		properties.put("hibernate.show_sql", hibernateShowSql);
		properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);

		return properties;
	}

}

Below is the controller that handles the request and deligate the data to freemarker template

/**
 * 
 */
package com.spark.spring.controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.spark.spring.bo.FormFieldsBo;
import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
@Controller
@RequestMapping("/controller")
public class UIRenderingController {

	@Autowired
	FormFieldsBo formFieldsBo;

	@RequestMapping(value = "/renderUi", method = RequestMethod.GET)
	public ModelAndView getTestHit() {
		System.out
				.println("-------------------inside the test hit method-----------------");

		List<FormFieldsModel> formFieldsModels = formFieldsBo.getFormFields("login_form");
		ModelAndView modelAndView = new ModelAndView("login", "formFieldsModels", formFieldsModels);
		return modelAndView;
	}
}

below are the service(BO) object and DataAccess Layer(DAO)

Please note that the below code as both interface and its implementation.

/**
 * 
 */
package com.spark.spring.bo;

import java.util.List;

import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
public interface FormFieldsBo {

	public List<FormFieldsModel> getFormFields(String formId);
}


/**
 * 
 */
package com.spark.spring.bo.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spark.spring.bo.FormFieldsBo;
import com.spark.spring.dao.FormFieldsDao;
import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
@Service(value="formFieldsBo")
public class FormFieldsBoImpl implements FormFieldsBo{

	@Autowired
	FormFieldsDao formFieldsDao;
	
	@Override
	@Transactional
	public List<FormFieldsModel> getFormFields(String formId) {
		System.out.println("---------------------- inside the BoImpl ----------------------");
		return formFieldsDao.getFormFields(formId);
	}

	
}

/**
 * 
 */
package com.spark.spring.dao;

import java.util.List;

import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
public interface FormFieldsDao {

	public List<FormFieldsModel> getFormFields(String formId);
}

/**
 * 
 */
package com.spark.spring.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.spark.spring.dao.FormFieldsDao;
import com.spark.spring.model.FormFieldsModel;

/**
 * @author PavanKumar Mantha
 *
 */
@Repository(value="formFieldsDao")
public class FormFieldsDaoImpl implements FormFieldsDao{

	@Autowired
	HibernateTemplate hibernateTemplate;
	
	@Override
	public List<FormFieldsModel> getFormFields(String formId) {

		Query query = hibernateTemplate.getSessionFactory().getCurrentSession().createQuery("from FormFieldsModel f where f.formId = :formId ");
		query.setParameter("formId", formId);
		List<FormFieldsModel> formFields = query.list();
		
		return formFields;
	}

	
}

now here is the freemarker template that gets redered dynamically

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
table a:link {
		color: #666;
		font-weight: bold;
		text-decoration:none;
	}
	table a:visited {
		color: #999999;
		font-weight:bold;
		text-decoration:none;
	}
	table a:active,
	table a:hover {
		color: #bd5a35;
		text-decoration:underline;
	}
	table {
		font-family:Arial, Helvetica, sans-serif;
		color:#666;
		font-size:12px;
		text-shadow: 1px 1px 0px #fff;
		background:#eaebec;
		margin:20px;
		border:#ccc 1px solid;
	
		-moz-border-radius:3px;
		-webkit-border-radius:3px;
		border-radius:3px;
	
		-moz-box-shadow: 0 1px 2px #d1d1d1;
		-webkit-box-shadow: 0 1px 2px #d1d1d1;
		box-shadow: 0 1px 2px #d1d1d1;
		margin-left:auto;
		margin-right:auto;
		margin-top:120px;
	}
	table th {
		padding:21px 25px 22px 25px;
		border-top:1px solid #fafafa;
		border-bottom:1px solid #e0e0e0;
	
		background: #ededed;
		background: -webkit-gradient(linear, left top, left bottom, from(#ededed), to(#ebebeb));
		background: -moz-linear-gradient(top,  #ededed,  #ebebeb);
	}
	table th:first-child {
		text-align: left;
		padding-left:20px;
	}
	table tr:first-child th:first-child {
		-moz-border-radius-topleft:3px;
		-webkit-border-top-left-radius:3px;
		border-top-left-radius:3px;
	}
	table tr:first-child th:last-child {
		-moz-border-radius-topright:3px;
		-webkit-border-top-right-radius:3px;
		border-top-right-radius:3px;
	}
	table tr {
		text-align: center;
		padding-left:20px;
	}
	table td:first-child {
		text-align: left;
		padding-left:20px;
		border-left: 0;
	}
	table td {
		padding:18px;
		border-top: 1px solid #ffffff;
		border-bottom:1px solid #e0e0e0;
		border-left: 1px solid #e0e0e0;
	
		background: #fafafa;
		background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));
		background: -moz-linear-gradient(top,  #fbfbfb,  #fafafa);
	}
	table tr.even td {
		background: #f6f6f6;
		background: -webkit-gradient(linear, left top, left bottom, from(#f8f8f8), to(#f6f6f6));
		background: -moz-linear-gradient(top,  #f8f8f8,  #f6f6f6);
	}
	table tr:last-child td {
		border-bottom:0;
	}
	table tr:last-child td:first-child {
		-moz-border-radius-bottomleft:3px;
		-webkit-border-bottom-left-radius:3px;
		border-bottom-left-radius:3px;
	}
	table tr:last-child td:last-child {
		-moz-border-radius-bottomright:3px;
		-webkit-border-bottom-right-radius:3px;
		border-bottom-right-radius:3px;
	}
	table tr:hover td {
		background: #f2f2f2;
		background: -webkit-gradient(linear, left top, left bottom, from(#f2f2f2), to(#f0f0f0));
		background: -moz-linear-gradient(top,  #f2f2f2,  #f0f0f0);	
	}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="javascript">
	$( document ).ready(function() {
		console.log( "ready!" );
		$("#loginButton").click(function(){
			alert('button clicked !');
		});
	});
</script>
</head>
<body>
	<table class="pretty">
		<#list formFieldsModels as formField>
		<tr>
			<#if formField.fieldType == 'text'>
				<td>${formField.fieldLabel}:</td><td><input type="${formField.fieldType}"/><td>
			</#if>
			<#if formField.fieldType == 'password'>
				<td>${formField.fieldLabel}:</td><td><input type="${formField.fieldType}"/></td>
			</#if>
			<#if formField.fieldType == 'button'>
				<td></td><td><input type="${formField.fieldType}" value="${formField.fieldLabel}" id="loginButton"/></td>
			</#if>
		</tr>
		</#list>
	</table>
</body>
</html>

here is the screenshots of the database and the final output.
database

login_ui

Happy Coding (Dynamic UI) πŸ™‚

FusionCharts+Spring+Ajax calls

Hello all, in this post i am going to take you on a tour how to render fusion charts data dynamically. In my previous post i explained rendering data statically. Here i explain how to make Ajax calls, using ajax we are going to populate region,country. Based on the region and country we get the oilConsumedByCountry by year and change this data based on the country changed, and create a dashboard which displays “Pie and Bar” charts.

*Note: This post assumes you already downloaded FusionCharts API and Maven
Following is the script for creating db table.

DROP TABLE IF EXISTS `test`.`oilconsumebycountry`;
CREATE TABLE  `test`.`oilconsumebycountry` (
  `Region` varchar(45) NOT NULL,
  `Country` varchar(45) NOT NULL,
  `Fipscd` varchar(45) NOT NULL,
  `year_1980` double NOT NULL,
  `year_1981` double DEFAULT NULL,
  `year_1982` double DEFAULT NULL,
  `year_1983` double DEFAULT NULL,
  `year_1984` double DEFAULT NULL,
  `year_1985` double DEFAULT NULL,
  `year_1986` double DEFAULT NULL,
  `year_1987` double DEFAULT NULL,
  `year_1988` double DEFAULT NULL,
  `year_1989` double DEFAULT NULL,
  `year_1990` double DEFAULT NULL,
  `year_1991` double DEFAULT NULL,
  `year_1992` double DEFAULT NULL,
  `year_1993` double DEFAULT NULL,
  `year_1994` double DEFAULT NULL,
  `year_1995` double DEFAULT NULL,
  `year_1996` double DEFAULT NULL,
  `year_1997` double DEFAULT NULL,
  `year_1998` double DEFAULT NULL,
  `year_1999` double DEFAULT NULL,
  `year_2000` double DEFAULT NULL,
  `year_2001` double DEFAULT NULL,
  `year_2002` double DEFAULT NULL,
  `year_2003` double DEFAULT NULL,
  `year_2004` double DEFAULT NULL,
  `year_2005` double DEFAULT NULL,
  `year_2006` double DEFAULT NULL,
  `year_2007` double DEFAULT NULL,
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

lets have a look at configuration files applicationContext.xml,spring-context.xml,hibernate-cfg.xml,web.xml respectively.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

	<context:component-scan base-package="com.spark.spring"></context:component-scan>
	<context:annotation-config />
	<tx:annotation-driven />
	
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
		<property name="password" value="root"></property>
		<property name="username" value="root"></property>
	</bean>

	<bean id="getCountryByCode" class="com.spark.spring.dao.GetCountryByCode">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property ref="dataSource" name="dataSource"></property>
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
		<property name="configurationClass">
			<value>org.hibernate.cfg.AnnotationConfiguration</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
</beans>

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<context:annotation-config />
	<context:component-scan base-package="com.spark.spring"></context:component-scan>
	
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="suffix">
			<beans:value>.jsp</beans:value>
		</beans:property>
		<beans:property name="prefix">
			<beans:value>/</beans:value>
		</beans:property>
	</beans:bean>

</beans:beans>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory>
		<mapping class="com.spark.spring.model.Oilconsumebycountry" />
	</session-factory>
</hibernate-configuration>
<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">

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	
	<servlet>
		<servlet-name>springServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-context.xml</param-value>
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>springServlet</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>ajaxView.jsp</welcome-file>
	</welcome-file-list>
</web-app>

GlobalAjaxController.java
This controller calls the DAO layes to fetch the data required by client and converts it to JSON format and returns it back to client.

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

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spark.spring.dao.OilconsumebycountryDAO;
import com.spark.spring.model.Oilconsumebycountry;

/**
 * @author Sony
 *
 */
@Controller
@RequestMapping(value="/load/**")
public class GlobalAjaxController {
	
	@Autowired
	OilconsumebycountryDAO oilconsumebycountryDAO;

	@RequestMapping(value="/load/allreagions")
	protected @ResponseBody String loadRegions(){

		List<String> regions = oilconsumebycountryDAO.getAllRegions();
		JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( regions );  
		return jsonArray.toString();
	}
	
	@RequestMapping(value="/load/{region}")
	protected @ResponseBody String loadCountriesByregion(@PathVariable String region){

		List<String> regions = oilconsumebycountryDAO.getCountriesByRegion(region);
		JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( regions );  
		return jsonArray.toString();
	}
	
	@RequestMapping(value="/load/{region}/{country}")
	protected @ResponseBody String loadConsuptionByCountryAndRegion(@PathVariable String region,@PathVariable String country){

		Oilconsumebycountry oilconsumebycountry = oilconsumebycountryDAO.getAllOilConsumedByCountriesAndRegion(region, country);
		
		String consuption = "{}";
		List<Double> oil = new ArrayList<Double>();
		oil.add(oilconsumebycountry.getYear1980());
		oil.add(oilconsumebycountry.getYear1981());
		oil.add(oilconsumebycountry.getYear1982());
		oil.add(oilconsumebycountry.getYear1983());
		oil.add(oilconsumebycountry.getYear1984());
		oil.add(oilconsumebycountry.getYear1985());
		oil.add(oilconsumebycountry.getYear1986());
		oil.add(oilconsumebycountry.getYear1987());
		oil.add(oilconsumebycountry.getYear1988());
		oil.add(oilconsumebycountry.getYear1989());
		oil.add(oilconsumebycountry.getYear1990());
		oil.add(oilconsumebycountry.getYear1991());
		oil.add(oilconsumebycountry.getYear1992());
		oil.add(oilconsumebycountry.getYear1993());
		oil.add(oilconsumebycountry.getYear1994());
		oil.add(oilconsumebycountry.getYear1995());
		oil.add(oilconsumebycountry.getYear1996());
		oil.add(oilconsumebycountry.getYear1997());
		oil.add(oilconsumebycountry.getYear1998());
		oil.add(oilconsumebycountry.getYear1999());
		oil.add(oilconsumebycountry.getYear2000());
		oil.add(oilconsumebycountry.getYear2001());
		oil.add(oilconsumebycountry.getYear2002());
		oil.add(oilconsumebycountry.getYear2003());
		oil.add(oilconsumebycountry.getYear2004());
		oil.add(oilconsumebycountry.getYear2005());
		oil.add(oilconsumebycountry.getYear2006());
		oil.add(oilconsumebycountry.getYear2007());
		
		JSONObject jsonObject = (JSONObject)JSONSerializer.toJSON(consuption);
		JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(oil);
		jsonObject.put("consuption", jsonArray);
		System.out.println(jsonObject);
		return jsonObject.toString();
	}
}

OilconsumebycountryDAO.java

/**
 * 
 */
package com.spark.spring.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.spark.spring.model.Oilconsumebycountry;

/**
 * @author Sony
 *
 */
@Repository(value="oilconsumebycountryDAO")
public class OilconsumebycountryDAO extends HibernateDaoSupport{

	@Autowired
	public void init(SessionFactory sessionFactory){
		setSessionFactory(sessionFactory);
	}
	
	public Oilconsumebycountry getAllOilConsumedByCountriesAndRegion(String region,String country){
		List<Integer> id = null;
		String hql = "select o.id from Oilconsumebycountry o where o.region=:region and o.country=:country";
		Session session = getHibernateTemplate().getSessionFactory().openSession();
		Query query = session.createQuery(hql);
		query.setParameter("region", region);
		query.setParameter("country", country);
		id = query.list();
		session.close();
		Oilconsumebycountry oilconsumebycountry = getHibernateTemplate().get(Oilconsumebycountry.class, id.get(0));
		return oilconsumebycountry;
	}
	
	public List<String> getCountriesByRegion(String region){
		List<String> countries = null;
		String hql = "select distinct o.country from Oilconsumebycountry o where o.region=:region";
		try {
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Query query = session.createQuery(hql);
			query.setParameter("region", region);
			countries = query.list();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return countries;
	}
	
	public List<String> getAllRegions(){
		List<String> regions = null;
		String hql = "select distinct o.region from Oilconsumebycountry o";
		try {
			Session session = getHibernateTemplate().getSessionFactory().openSession();
			Query query = session.createQuery(hql);
			regions = query.list();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
		return regions;
	}
}

Oilconsumebycountry.java

package com.spark.spring.model;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * <p>
 * Pojo mapping TABLE oilconsumebycountry
 * </p>
 * <p>
 * </p>
 * 
 * <p>
 * Generated at Sun Jul 07 16:38:56 IST 2013
 * </p>
 * 
 * @author Sony 
 * 
 */
@Entity
@Table(name = "oilconsumebycountry", catalog = "test")
@SuppressWarnings("serial")
public class Oilconsumebycountry implements Serializable {

	/**
	 * Attribute region.
	 */
	private int id;
	/**
	 * Attribute region.
	 */
	private String region;

	/**
	 * Attribute country.
	 */
	private String country;

	/**
	 * Attribute fipscd.
	 */
	private String fipscd;

	/**
	 * Attribute year1980.
	 */
	private Double year1980;

	/**
	 * Attribute year1981.
	 */
	private Double year1981;

	/**
	 * Attribute year1982.
	 */
	private Double year1982;

	/**
	 * Attribute year1983.
	 */
	private Double year1983;

	/**
	 * Attribute year1984.
	 */
	private Double year1984;

	/**
	 * Attribute year1985.
	 */
	private Double year1985;

	/**
	 * Attribute year1986.
	 */
	private Double year1986;

	/**
	 * Attribute year1987.
	 */
	private Double year1987;

	/**
	 * Attribute year1988.
	 */
	private Double year1988;

	/**
	 * Attribute year1989.
	 */
	private Double year1989;

	/**
	 * Attribute year1990.
	 */
	private Double year1990;

	/**
	 * Attribute year1991.
	 */
	private Double year1991;

	/**
	 * Attribute year1992.
	 */
	private Double year1992;

	/**
	 * Attribute year1993.
	 */
	private Double year1993;

	/**
	 * Attribute year1994.
	 */
	private Double year1994;

	/**
	 * Attribute year1995.
	 */
	private Double year1995;

	/**
	 * Attribute year1996.
	 */
	private Double year1996;

	/**
	 * Attribute year1997.
	 */
	private Double year1997;

	/**
	 * Attribute year1998.
	 */
	private Double year1998;

	/**
	 * Attribute year1999.
	 */
	private Double year1999;

	/**
	 * Attribute year2000.
	 */
	private Double year2000;

	/**
	 * Attribute year2001.
	 */
	private Double year2001;

	/**
	 * Attribute year2002.
	 */
	private Double year2002;

	/**
	 * Attribute year2003.
	 */
	private Double year2003;

	/**
	 * Attribute year2004.
	 */
	private Double year2004;

	/**
	 * Attribute year2005.
	 */
	private Double year2005;

	/**
	 * Attribute year2006.
	 */
	private Double year2006;

	/**
	 * Attribute year2007.
	 */
	private Double year2007;

        // Generate Getters and Setters..

}

This is the JSP file used as view, data from controller is rendered here using a jquery script.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script
	src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="inner_js/FusionCharts.js"></script>
<script src="inner_js/inner_js.js"></script>
</head>
<body>
	<table>
		<tr>
			<td>Regions:<select id="regions" name="regions"></select></td>
			<td>Countries:<select id="country" name="country"></select></td>
		</tr>
	</table>
	<div style="width: 1300px;">
		<div id="piechartContainer" style="float: left; width: 600px;">FusionCharts
			XT will load here!</div>
		<div id="barchartContainer" style="float: right; width: 600px;">FusionCharts
			XT will load here!</div>
		<br style="clear: left;" />
	</div>
</body>
</html>

This is the javascript file from which the Ajax calls are fired to the controller, and data is collected by this script and rendered into view.

$(document).ready(function(){
	$.ajax({
		url:"http://localhost:8080/SpringFusionCharts/spring/load/allreagions",
		dataType:"json",
		success:function(data){
			var options = '<option>----select----</option>';
		      for (var i = 0; i < data.length; i++) {
		        options += '<option value="' + data[i] + '">' + data[i] + '</option>';
		      }
		      $("#regions").html(options);

		},error:function(data){
		}
	});
	
	$("#regions").on("change",function(){
		$.ajax({
			url:"http://localhost:8080/SpringFusionCharts/spring/load/"+$(this).val(),
			dataType:"json",
			success:function(data){
				var options = '<option>----select----</option>';
			      for (var i = 0; i < data.length; i++) {
			        options += '<option value="' + data[i] + '">' + data[i] + '</option>';
			      }
			      $("#country").html(options);

			},error:function(data){
			}
		});
	});
	
	$("#country").on("change",function(){
		var dataStr = {
				'chart' : {
					'caption' : 'oil consumed by country',
					'xAxisName' : 'years',
					'yAxisName' : 'consuption',
					'numberPrefix' : ''
				},
				'data' : [ ]
			};
		var dataObjectArray = new Array();
		
		var myPieChart = new FusionCharts("Charts/Pie3D.swf",
				"myChartId", "750", "450", "0");
		var myBarChart = new FusionCharts("Charts/Column3D.swf",
				"myChartId2", "750", "450", "0");
		$.ajax({
			url:"http://localhost:8080/SpringFusionCharts/spring/load/"+$("#regions").val()+"/"+$(this).val(),
			dataType:"json",
			success:function(data){
				var i = 1980;
				$.each(data.consuption, function(key, value) {
					var dataObject = {
							label:'',
							value:''
						};
					dataObject.label = "year_"+i;
					dataObject.value = value;
					dataObjectArray.push(dataObject);
					i++;
				});
				dataStr.data = dataObjectArray;
				myPieChart.setJSONData(dataStr);
				myPieChart.render("piechartContainer");

				myBarChart.setJSONData(dataStr);
				myBarChart.render("barchartContainer");
			},error:function(data){
			}
		});
		
	});
});

Output1:
data1

Output2:
After changing the region and country the data changes dynamically.
data2
Happy Coding πŸ™‚

Spring3+Hibernate3+FusionChartsXT for reporting

Hello all, from past few days i was working on some reports and dashboards so the requirement is to call some spring services, which return the data in the form of JSON. my responsibility is to receive the JSON data and feed it to correct chart and render it so im here to share my experience in the form of small example.

please create a database as shown below:

DROP TABLE IF EXISTS `test`.`maps`;
CREATE TABLE  `test`.`maps` (
  `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `STATE_NAME` varchar(100) NOT NULL,
  `STATE_CODE` varchar(10) NOT NULL,
  `POPULATION` varchar(5) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

please download the fusionchartsXT latest(trail) version from here, after you download, create a mavanized project in eclipse.
In the pom.xml please add the below content.

<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.spark.spring.fusioncharts</groupId>
	<artifactId>SpringFusionCharts</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SpringFusionCharts</name>
	<description>SpringFusionCharts</description>

	<properties>
		<jdk.version>1.6</jdk.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
			<version>3.2.0.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.1</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>
		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<classifier>jdk15</classifier>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate</artifactId>
			<version>3.5.4-Final</version>
			<type>pom</type>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-annotations</artifactId>
			<version>3.5.4-Final</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.15</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.5.6</version>
		</dependency>
		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.12.1.GA</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringFusionCharts</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-eclipse-plugin</artifactId>
				<version>2.9</version>
				<configuration>
					<downloadSources>true</downloadSources>
					<downloadJavadocs>false</downloadJavadocs>
					<wtpversion>2.0</wtpversion>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

once this step is done all your dependencies(jar files) are managed my maven.now go and create “WEB-INF,charts,javascript” folders in src/main/webapp. In WEB-INF please put web.xml as follows.

<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">

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-context.xml</param-value>
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/spring/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

After this step please extract the downloaded FusionChartsXT.zip in desired location, from that navigate to the folder charts, copy all the swf files and put them in the charts folder of your eclipse(src/main/webapp/charts)
now again from the FusionChartsXT home copy “FusionCharts.js,Jquery.min.js” and put them in javascript folder of your eclipse.
Now it’s time to code logic.Lets integrate Spring and Hibernate to query the database and here i transform the
result from database to JSON format, and return that to JSP.

Note: please create separate packages for interfaces and their implementations as it gives the project a clear separation between layers(good practice)

Let us see the ServiceLayer:

package com.spark.spring.fusioncharts.service;

import java.util.List;

import com.spark.spring.fusioncharts.model.Maps;

public interface GetStatasticsDataService {

	public List<Maps> getPopulationByCountry();
}

/**
 * 
 */
package com.spark.spring.fusioncharts.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spark.spring.fusioncharts.dao.GetStatasticsData;
import com.spark.spring.fusioncharts.model.Maps;
import com.spark.spring.fusioncharts.service.GetStatasticsDataService;

/**
 * @author Sony
 *
 */
@Service(value="GetStatasticsDataServiceImpl")
public class GetStatasticsDataServiceImpl implements GetStatasticsDataService {

	@Autowired
	GetStatasticsData getStatasticsData;
	
	/* (non-Javadoc)
	 * @see com.spark.spring.fusioncharts.service.GetStatasticsDataService#getOilConsumebyCountry()
	 */
	@Override
	public List<Maps> getPopulationByCountry() {
		
		return getStatasticsData.getOilConsumebyCountry();
	}

}

Let us see the DAOLayer:

/**
 * 
 */
package com.spark.spring.fusioncharts.dao;

import java.util.List;

import com.spark.spring.fusioncharts.model.Maps;

/**
 * @author Sony
 *
 */
public interface GetStatasticsData {

	public List<Maps> getPopulationByCountry();
}

/**
 * 
 */
package com.spark.spring.fusioncharts.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.spark.spring.fusioncharts.dao.GetStatasticsData;
import com.spark.spring.fusioncharts.model.Maps;

/**
 * @author Sony
 *
 */
@Repository(value="GetStatasticsDataImpl")
public class GetStatasticsDataImpl extends HibernateDaoSupport implements GetStatasticsData{

	@Autowired
	public void init(SessionFactory factory) {
	    setSessionFactory(factory);
	}
	
	@Override
	public List<Maps> getPopulationByCountry() {
		
		List<Maps> mapsList = getHibernateTemplate().loadAll(Maps.class);
		return mapsList;
	}

}

Let us see the ModelLayer:

package com.spark.spring.fusioncharts.model;

import java.io.Serializable;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * <p>Pojo mapping TABLE maps</p>
 * <p></p>
 *
 * <p>Generated at Sun Jun 30 20:56:48 IST 2013</p>
 * @author Salto-db Generator v1.0.16 / EJB3
 * 
 */
@Entity
@Table(name = "maps")
@SuppressWarnings("serial")
public class Maps implements Serializable {

	/**
	 * Attribute id.
	 */
	private Integer id;
	
	/**
	 * Attribute stateName.
	 */
	private String stateName;
	
	/**
	 * Attribute stateCode.
	 */
	private String stateCode;
	
	/**
	 * Attribute population.
	 */
	private String population;
	
	
	/**
	 * <p> 
	 * </p>
	 * @return id
	 */
	@Basic
	@Id
	@GeneratedValue
	@Column(name = "ID")
		public Integer getId() {
		return id;
	}

	/**
	 * @param id new value for id 
	 */
	public void setId(Integer id) {
		this.id = id;
	}
	
	/**
	 * <p> 
	 * </p>
	 * @return stateName
	 */
	@Basic
	@Column(name = "STATE_NAME", length = 100)
		public String getStateName() {
		return stateName;
	}

	/**
	 * @param stateName new value for stateName 
	 */
	public void setStateName(String stateName) {
		this.stateName = stateName;
	}
	
	/**
	 * <p> 
	 * </p>
	 * @return stateCode
	 */
	@Basic
	@Column(name = "STATE_CODE", length = 10)
		public String getStateCode() {
		return stateCode;
	}

	/**
	 * @param stateCode new value for stateCode 
	 */
	public void setStateCode(String stateCode) {
		this.stateCode = stateCode;
	}
	
	/**
	 * <p> 
	 * </p>
	 * @return population
	 */
	@Basic
	@Column(name = "POPULATION", length = 5)
		public String getPopulation() {
		return population;
	}

	/**
	 * @param population new value for population 
	 */
	public void setPopulation(String population) {
		this.population = population;
	}
}

Let us see the ControllerLayer:

/**
 * 
 */
package com.spark.spring.fusioncharts.controller;

import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spark.spring.fusioncharts.model.Maps;
import com.spark.spring.fusioncharts.service.GetStatasticsDataService;

/**
 * @author Sony
 *
 */
@Controller
public class ChartsController {
	
	@Autowired
	GetStatasticsDataService getStatasticsDataService;

	@RequestMapping(value="/charts")
	public @ResponseBody String getChartsDashboard(){
		List<Maps> oilconsumebycountries = getStatasticsDataService.getPopulationByCountry();
		JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(oilconsumebycountries);
		return jsonArray.toString();
	}
	
	

}

Now let’s start looking at the resource files inorder to configure the application.

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
            http://www.springframework.org/schema/jdbc
            http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

	<context:component-scan base-package="com.spark.spring.fusioncharts"></context:component-scan>
	<context:annotation-config></context:annotation-config>
	<mvc:annotation-driven></mvc:annotation-driven>

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/test" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
		<property name="configurationClass">
			<value>org.hibernate.cfg.AnnotationConfiguration</value>
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.show_sql">true</prop>
			</props>
		</property>
	</bean>
</beans>

spring-context

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<!-- Enables the Spring MVC @Controller programming Model -->
	<context:component-scan base-package="com.spark.spring.fusioncharts"></context:component-scan>
	<context:annotation-config></context:annotation-config>
	<annotation-driven></annotation-driven>

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix">
			<beans:value>/WEB-INF/pages/</beans:value>
		</beans:property>
		<beans:property name="suffix">
			<beans:value>.jsp</beans:value>
		</beans:property>

	</beans:bean>

</beans:beans>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <mapping class="com.spark.spring.fusioncharts.model.Maps" />
    </session-factory>
</hibernate-configuration>

log4j.properties

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D\:\\logger.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
 
# Root logger option
#log4j.rootLogger=debug, file, stdout
log4j.rootLogger=info, ROOT, file
#log4j.rootLogger=fatal, file, stdout
#log4j.rootLogger=ERROR, file, stdout

Now lets code the view(JSP) part of our project.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>spring3.2+Fusion Charts</title>
<script type="text/javascript" src="javascript/jquery.min.js"></script>
<script type="text/javascript" src="javascript/FusionCharts.js"></script>
<script type="text/javascript" src="javascript/Mycharts.js"></script>
</head>
<body>
	<div style="width: 1300px;">
		<div id="piechartContainer" style="float: left; width: 600px;">FusionCharts XT will load here!</div>
		<div id="barchartContainer" style="float: right; width: 600px;">FusionCharts XT will load here!</div>
		<br style="clear: left;" />
	</div>
	
	<div style="width: 1300px;">
		<div id="pyramidchartContainer" style="float: left; width: 600px;">FusionCharts XT will load here!</div>
		<div id="linechartContainer" style="float: right; width: 600px;">FusionCharts XT will load here!</div>
		<br style="clear: left;" />
	</div>

</body>
</html>

inorder to render the charts in our dashboard please write your own javascript code as follows
Mycharts.js

$(document).ready(
		function() {
			$.ajax({
				url : "http://localhost:8080/SpringMVC/spring/charts",
				dataType : "json",
				success : function(data) {
					
					var dataObjectArray = new Array();
					
					var myPieChart = new FusionCharts("Charts/Pie3D.swf",
							"myChartId", "750", "450", "0");
					var myBarChart = new FusionCharts("Charts/Column3D.swf",
							"myChartId2", "750", "450", "0");
					var myLineChart = new FusionCharts("Charts/Line.swf",
							"myChartId3", "750", "450", "0");
					var myPyramidChart = new FusionCharts("Charts/Pyramid.swf",
							"myChartId3", "750", "450", "0");

					var dataStr = {
						'chart' : {
							'caption' : 'population per state',
							'xAxisName' : 'states',
							'yAxisName' : 'population',
							'numberPrefix' : ''
						},
						'data' : [ ]
					};

					$.each(data, function(key, value) {
						//alert(value.population + "" + value.stateName);
						var dataObject = {
								label:'',
								value:''
							}
						dataObject.label = value.stateName;
						dataObject.value = value.population;
						dataObjectArray.push(dataObject);
					});
					
					dataStr.data = dataObjectArray;
					myPieChart.setJSONData(dataStr);
					myPieChart.render("piechartContainer");

					myBarChart.setJSONData(dataStr);
					myBarChart.render("barchartContainer");

					myLineChart.setJSONData(dataStr);
					myLineChart.render("linechartContainer");

					myPyramidChart.setJSONData(dataStr);
					myPyramidChart.render("pyramidchartContainer");

				},
				error : function(data) {

				}
			});
		});

once done please run the poject and in browser it shows as below. report of same data with four different charts.
FusionChartsReport

Happy Coding:)

Hibernate Inheritance: Table Per Concrete Class

Hi Guys now its time to look at Table per concrete class hierarchy in hibernate. lets have a scenario where we have three classes Bike,BikeDetails and BikeEngine is the super class to the other two classes.In One Table per Concrete class scheme, each concrete class is mapped as normal persistent class. Thus we have 3 tables; Bike, BikeDetails and BikeEngine to persist the class data. In this scheme, the mapping of the subclass repeats the properties of the parent class.

Advantages
This is the easiest method of Inheritance mapping to implement.

Disadvantages
Data thats belongs to a parent class is scattered across a number of subclass tables, which represents concrete classes.
This hierarchy is not recommended for most cases.
Changes to a parent class is reflected to large number of tables
A query couched in terms of parent class is likely to cause a large number of select operations

following is the sql script to create the database.

DROP TABLE IF EXISTS `test`.`bike`;
CREATE TABLE  `test`.`bike` (
  `bike_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `bike_name` varchar(45) NOT NULL,
  `company` varchar(45) NOT NULL,
  PRIMARY KEY (`bike_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `test`.`bike_details`;
CREATE TABLE  `test`.`bike_details` (
  `bike_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `bike_cost` int(10) unsigned NOT NULL,
  `manufacture_date` date NOT NULL,
  `bike_name` varchar(45) NOT NULL,
  `company` varchar(45) NOT NULL,
  PRIMARY KEY (`bike_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `test`.`bike_engine`;
CREATE TABLE  `test`.`bike_engine` (
  `bike_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `engine_type` varchar(45) NOT NULL,
  `engine_cc` varchar(45) NOT NULL,
  `engine_bhp` varchar(45) NOT NULL,
  `bike_name` varchar(45) NOT NULL,
  `company` varchar(45) NOT NULL,
  PRIMARY KEY (`bike_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Following is the example where we map Bike, BikeDetails and BikeEngine entity classes using XML mapping.
Bike.java

/**
 * 
 */
package com.spark.hibernate.model;

import java.io.Serializable;

/**
 * @author Sony
 * 
 */
public class Bike implements Serializable {

	private int bikeId;
	private String bikeName;
	private String company;
	
	public Bike() {
		// TODO Auto-generated constructor stub
	}
	
	public Bike(String bikeName,String company) {
		this.bikeName = bikeName;
		this.company = company;
	}

	/**
	 * @return the bikeId
	 */
	public int getBikeId() {
		return bikeId;
	}

	/**
	 * @param bikeId
	 *            the bikeId to set
	 */
	public void setBikeId(int bikeId) {
		this.bikeId = bikeId;
	}

	/**
	 * @return the bikeName
	 */
	public String getBikeName() {
		return bikeName;
	}

	/**
	 * @param bikeName
	 *            the bikeName to set
	 */
	public void setBikeName(String bikeName) {
		this.bikeName = bikeName;
	}

	/**
	 * @return the company
	 */
	public String getCompany() {
		return company;
	}

	/**
	 * @param company
	 *            the company to set
	 */
	public void setCompany(String company) {
		this.company = company;
	}

}

BikeDetails.java

/**
 * 
 */
package com.spark.hibernate.model;

import java.io.Serializable;
import java.util.Date;

/**
 * @author Sony
 * 
 */
public class BikeDetails extends Bike implements Serializable {

	private int bikeCost;
	private Date manufactureDate;

	public BikeDetails() {
		// TODO Auto-generated constructor stub
	}

	public BikeDetails(String bikeName, String company, int bikeCost,
			Date manufactureDate) {
		super(bikeName, company);
		this.bikeCost = bikeCost;
		this.manufactureDate = manufactureDate;
	}

	/**
	 * @return the bikeCost
	 */
	public int getBikeCost() {
		return bikeCost;
	}

	/**
	 * @param bikeCost
	 *            the bikeCost to set
	 */
	public void setBikeCost(int bikeCost) {
		this.bikeCost = bikeCost;
	}

	/**
	 * @return the manufactureDate
	 */
	public Date getManufactureDate() {
		return manufactureDate;
	}

	/**
	 * @param manufactureDate
	 *            the manufactureDate to set
	 */
	public void setManufactureDate(Date manufactureDate) {
		this.manufactureDate = manufactureDate;
	}

}

BikeEngine.java

/**
 * 
 */
package com.spark.hibernate.model;

import java.io.Serializable;

/**
 * @author Sony
 * 
 */
public class BikeEngine extends Bike implements Serializable {

	private String engineType;
	private String engineBHP;
	private String engineCC;

	public BikeEngine() {
		// TODO Auto-generated constructor stub
	}

	public BikeEngine(String bikeName, String company, String engineType,
			String engineBHP, String engineCC) {
		super(bikeName, company);
		this.engineType = engineType;
		this.engineBHP = engineBHP;
		this.engineCC = engineCC;
	}

	/**
	 * @return the engineType
	 */
	public String getEngineType() {
		return engineType;
	}

	/**
	 * @param engineType
	 *            the engineType to set
	 */
	public void setEngineType(String engineType) {
		this.engineType = engineType;
	}

	/**
	 * @return the engineBHP
	 */
	public String getEngineBHP() {
		return engineBHP;
	}

	/**
	 * @param engineBHP
	 *            the engineBHP to set
	 */
	public void setEngineBHP(String engineBHP) {
		this.engineBHP = engineBHP;
	}

	/**
	 * @return the engineCC
	 */
	public String getEngineCC() {
		return engineCC;
	}

	/**
	 * @param engineCC
	 *            the engineCC to set
	 */
	public void setEngineCC(String engineCC) {
		this.engineCC = engineCC;
	}

}

lets construct a hbm file with multiple classes mappings as follows.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 17 Jun, 2013 9:42:56 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping package="com.spark.hibernate.model">

	<class name="Bike" table="BIKE">
		<id name="bikeId" type="int">
			<column name="BIKE_ID" />
			<generator class="native" />
		</id>
		<property name="bikeName" type="java.lang.String">
			<column name="BIKE_NAME" />
		</property>
		<property name="company" type="java.lang.String">
			<column name="COMPANY" />
		</property>
	</class>

	<class name="BikeDetails" table="BIKE_DETAILS">
		<id name="bikeId" type="int">
			<column name="BIKE_ID" />
			<generator class="native" />
		</id>
		<property name="bikeCost" column="bike_cost"></property>
		<property name="manufactureDate" column="manufacture_date"
			type="date"></property>
		<property name="bikeName" column="bike_name"></property>
		<property name="company" column="company"></property>
	</class>

	<class name="BikeEngine" table="BIKE_ENGINE">
		<id name="bikeId" type="int">
			<column name="BIKE_ID" />
			<generator class="native" />
		</id>
		<property name="engineType" column="engine_type"></property>
		<property name="engineCC" column="engine_cc"></property>
		<property name="engineBHP" column="engine_bhp"></property>
		<property name="bikeName" column="bike_name"></property>
		<property name="company" column="company"></property>
	</class>
	
</hibernate-mapping>

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.password">root</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.query.startup_check">true</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.use_sql_comments">true</property>
  <property name="hibernate.format_sql">true</property>
  
  <mapping resource="com/spark/hibernate/model/Bike.hbm.xml"/>
  
 </session-factory>
</hibernate-configuration>

Main.java

/**
 * 
 */
package com.spark.hibernate.main;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.spark.hibernate.model.Account;
import com.spark.hibernate.model.AccountHolder;
import com.spark.hibernate.model.AccountTransactions;
import com.spark.hibernate.model.Bike;
import com.spark.hibernate.model.BikeDetails;
import com.spark.hibernate.model.BikeEngine;
import com.spark.hibernate.util.HibernateUtil;

/**
 * @author Sony
 *
 */
public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Logger logger = LoggerFactory.getLogger(Main.class);
		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		logger.info("-----------------Session created------------------");
		session.beginTransaction();
		logger.info("-----------------Transaction Started------------------");
		
		Bike bike = new Bike("R15", "Yamaha");
		session.persist(bike);
		logger.info("-------------Bike Object Persisted----------");
		
		BikeEngine bikeEngine = new BikeEngine("R15", "Yamaha","OilCooled","10.5","180");
		session.persist(bikeEngine);
		logger.info("-------------BikeEngine Object Persisted----------");
		
		BikeDetails bikeDetails = new BikeDetails("R15", "Yamaha",48000,new Date());
		session.persist(bikeDetails);
		logger.info("-------------BikeDetails Object Persisted----------");
		
		session.getTransaction().commit();
		logger.info("-----------------Transaction Commited------------------");
		session.close();
		logger.info("-----------------Session Closed------------------");
		sessionFactory.close();
		logger.info("-----------------SessionFactory Closed------------------");
		
	}

}

note:get the HibernateUtil from the previous posts
output:
Table_Per_Concrete_Class
That is it,
Happy Coding πŸ™‚