Spring Integration with JPA/Hibernate using maven – I

Hi all here is my post regarding integration of some of the best frameworks available in the market, Spring+JPA/Hibernate.
Spring’s Basic concept: Inversion of Control

The basic concept of spring is the Inversion of Control pattern (dependency injection). In Spring, programmers don’t need to create user objects but they need to describe how they should be created (in applicationContext.xml or using annotations). Programmers need not directly connect components and services together in code but describe which services are needed by which components in a configuration file or using annotations. The spring container is responsible for all this. Spring creates all the objects, connects them together by setting the necessary properties, and determines when methods will be invoked.
So using Spring framework the integration between technologies become loosely coupled.

Requirements:
Spring 3.1
JPA2.x/Hibernate 3.x
Eclipse 4.2 with Maven
Mysql Database

The major parts of the Credentials application explained below are:

The Entity classes
The DAO class which will contain common db operation code and functions
The service class – which is the actual business class.. This will contain actual business logic in it. In our example, we save Credentials bean information using this class.
Explained in the next tutorial
The client – The client can be a jsp / jsf web components or it can be a simple java program, which gets the service bean from spring and calls business method.
The spring’s applicationContext.xml descriptor which specifies what are the objects to be created when starting the application and where they should be injected.

Let’s go through the tutorial step by step.You can download the full project code at the end of the tutorial:
i explain how to Retrieve and Insert and leave Delete and Update to be coded yourself(for fun).

Step1:create a maven project in eclipse.
step2:update the pom.xml file as shown below.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spark.spring</groupId>
	<artifactId>SpringIntegration</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>SpringIntegration</name>
	<description>SpringIntegration</description>

	<properties>
		<org.slf4j-version>1.6.1</org.slf4j-version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ezmorph</groupId>
			<artifactId>ezmorph</artifactId>
			<version>1.0.6</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>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.18</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>
		<!-- Spring Security -->
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>3.1.0.RELEASE</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-crypto</artifactId>
			<version>3.1.0.RELEASE</version>
		</dependency>

		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
			<scope>runtime</scope>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.6.10</version>
		</dependency>


		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<!-- Hibernate Validator -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.0.0.GA</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.2.0.CR1</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>3.4.0.GA</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>3.1.1.RELEASE</version>
		</dependency>

	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.0-beta-1</version>
			</plugin>
			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>7.4.0.v20110414</version>
				<configuration></configuration>
			</plugin>
		</plugins>
		<pluginManagement>
			<plugins>
				<!--This plugin's configuration is used to store Eclipse m2e settings 
					only. It has no influence on the Maven build itself. -->
				<plugin>
					<groupId>org.eclipse.m2e</groupId>
					<artifactId>lifecycle-mapping</artifactId>
					<version>1.0.0</version>
					<configuration>
						<lifecycleMappingMetadata>
							<pluginExecutions>
								<pluginExecution>
									<pluginExecutionFilter>
										<groupId>
											org.apache.maven.plugins
										</groupId>
										<artifactId>
											maven-compiler-plugin
										</artifactId>
										<versionRange>
											[2.3.2,)
										</versionRange>
										<goals>
											<goal>compile</goal>
											<goal>testCompile</goal>
										</goals>
									</pluginExecutionFilter>
									<action>
										<ignore></ignore>
									</action>
								</pluginExecution>
							</pluginExecutions>
						</lifecycleMappingMetadata>
					</configuration>
				</plugin>
			</plugins>
		</pluginManagement>
	</build>
	<!-- needed for XmlSchema -->
	<repositories>
		<repository>
			<id>ibiblio</id>
			<name>ibiblio maven repository</name>
			<url>http://ibiblio.org/maven/</url>
			<layout>legacy</layout>
		</repository>
		<repository>
			<id>apache</id>
			<name>Apache maven repository</name>
			<url>http://www.apache.org/dist/java-repository/</url>
			<layout>legacy</layout>
		</repository>
	</repositories>

</project>

Step3:put web.xml in src/main/webapp/WEB-INF/ as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- Defines all the spring context information for all servlets and Filters 
		that share the info -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:application-context.xml</param-value>
	</context-param>

	<!-- creates spring container listener shared by all servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- request processing servlet -->
	<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>pages/index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

put all the configuration files in the src/main/resources folder of your maven project.

Step4: lets code our first configuration file “application-context.xml” as shown below.

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- component scan for @component,@Repositry,@Service -->
	<context:component-scan base-package="com.spark" />
	
	<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>

	<!-- JPA EntityManagerFactory -->
	<bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
		p:dataSource-ref="dataSource">
		<property name="persistenceUnitName" value="MyPersistenceUnit"/> 
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="database" value="MYSQL" />
				<property name="showSql" value="true" />
			</bean>
		</property>
	</bean>

	<!-- Transaction manager for a single JPA EntityManagerFactory (alternative 
		to JTA) -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
		p:entityManagerFactory-ref="entityManagerFactory" />

	<!-- Activates various annotations to be detected in bean classes for eg 
		@Autowired -->
	<context:annotation-config />

	<!-- enable the configuration of transactional behavior based on annotations -->
	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />

	<!-- Property Configurator -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:jdbc.properties" />
	</bean>

</beans>

Step5:lets code our second configuration file “spring-context.xml” which internally imports one more configuration file “controllers.xml”, this spring-context.xml file goes as a parameter for DispatcherServlet class of Spring framework.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
        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
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- Enables the Spring MVC @Controller programming Model -->
	<annotation-driven />

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/" />
		<beans:property name="suffix" value=".html" />
	</beans:bean>

	<!-- Imports user-defined @Controller beans that process client requests -->
	<beans:import resource="controllers.xml" />

</beans:beans>

Step6: controllers.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

	<!-- Activates various annotations to be detected in bean classes -->	
	<context:annotation-config />
	<context:spring-configured />
	<!-- enable the configuration of transactional behavior based on annotations -->
	<tx:annotation-driven/>

	<!-- Scans within the base package of the application for @Components to configure as beans -->
	<context:component-scan base-package="com.spark" />
	
	
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- one of the properties available; the maximum file size in bytes -->
		<property name="maxUploadSize" value="10000000" />
	</bean>
	
	
</beans>

Step7: Lets put the log4j.properties


log4j.rootCategory=debug, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=C://templog/clinicComponet.log
log4j.appender.logfile.MaxFileSize=1MB

# Keep three backup files
log4j.appender.logfile.MaxBackupIndex=3
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout

#Pattern to output : date priority [category] - <message>line_separator
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - <%m>%n

So now we have finished coding our configuration just start with our logic
create the followiing packages in src/main/java folder of maven project as follows.

com.spark.controller
com.spark.dao
com.spark.service
com.spark.model

Lets start coding Java now. first step is coding our model class(POJO) as below.

/**
 * 
 */
package com.spark.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.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 * @author Sony
 * 
 */

@Entity
@Table(name = "credentials")
@NamedQueries({
@NamedQuery(name="Credentials.getAllRecords",
    query="SELECT o FROM Credentials o")          
})
public class Credentials implements Serializable{

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name = "ID")
	private int id;

	@Column(name = "username")
	private String username;

	@Column(name = "password")
	private String password;

	public int getId() {
		return id;
	}

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

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}

once our pojo is ready lets decide the business logic that is our service class. we will code an interface and its implementation class as follows

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

import java.util.List;

import com.spark.model.Credentials;

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

    void save(Credentials credentials);
    Credentials findById(Long id);       
    List<Credentials> findAll();   
}

and following is the implementation class

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

import java.util.List;

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

import com.spark.dao.CredentialsDao;
import com.spark.dao.CredentialsDaoImpl;
import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
@Service("credentialService")
public class CredentialsServiceImpl implements CredentialsService {

	@Autowired
	CredentialsDao credentialsDao;
	
	public CredentialsDao getCredentialsDao() {
		return credentialsDao;
	}

	public void setCredentialsDao(CredentialsDao credentialsDao) {
		this.credentialsDao = credentialsDao;
	}

	/* (non-Javadoc)
	 * @see com.spark.service.CredentialsService#save(com.spark.model.Credentials)
	 */
	@Override
	public void save(Credentials credentials) {
		// TODO Auto-generated method stub
		credentialsDao.save(credentials);

	}

	/* (non-Javadoc)
	 * @see com.spark.service.CredentialsService#findById(java.lang.Long)
	 */
	@Override
	public Credentials findById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.spark.service.CredentialsService#findAll()
	 */
	@Override
	public List<Credentials> findAll() {
		// TODO Auto-generated method stub
		return credentialsDao.findAll();
	}

}

Now its time to code our core database logic. The database logic is handled by JPA EntityManager, the object is injected into the EntityManager using the @PersistenceContext annotation its the responsibility of the Spring container to inject the EntityManager Implementation object after it scans the annotation. We will code the dao layer same as we did with service layer with an interface and its implementation class. please note that the dao is annotated as @Transactional that means the database operations will be executed under a transactional context
when spring scans the annotation.

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

import java.util.List;

import com.spark.model.Credentials;

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

    public List<Credentials> findAll();
    public void save(Credentials credentials);
    public Credentials findById(int id);

}

following is the implementation class for the interface.

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

import java.util.List;

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

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

import com.spark.model.Credentials;

/**
 * @author Sony
 *
 */
@Transactional
@Component
public class CredentialsDaoImpl implements CredentialsDao {
	
	@PersistenceContext
	private EntityManager entityManager;

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/* (non-Javadoc)
	 * @see com.spark.dao.CredentialsDao#findAll()
	 */
	@Override
	public List<Credentials> findAll() {
		// TODO Auto-generated method stub
		List<Credentials> credentials = null;
		try {
			credentials = entityManager.createNamedQuery("Credentials.getAllRecords").getResultList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return credentials;
	}

	/* (non-Javadoc)
	 * @see com.spark.dao.CredentialsDao#save(com.spark.model.Credentials)
	 */
	@Override
	public void save(Credentials credentials) {
		// TODO Auto-generated method stub
		try {
			
			entityManager.persist(credentials);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/* (non-Javadoc)
	 * @see com.spark.dao.CredentialsDao#findById(int)
	 */
	@Override
	public Credentials findById(int id) {
		// TODO Auto-generated method stub
		return null;
	}

}

Now its time to code controller which is responsible for deligating the requests to service layer and there to dao layer. In the retrieve method the response returned from the method will be a JSON String

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

import java.util.List;

import javax.validation.Valid;

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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spark.model.Credentials;
import com.spark.service.CredentialsService;

/**
 * @author Sony
 *
 */
@Controller
public class SpringController {

	@Autowired(required=true)
	CredentialsService credentialsService;
	
	@RequestMapping(value="/insert",method=RequestMethod.POST)
	public @ResponseBody String handleInsertRequest(@Valid String username,@Valid String password){
		
		String returnStatus = "Details Saved Successfully";
				
		Credentials credentials = new Credentials();
		credentials.setUsername(username);
		credentials.setPassword(password);
		
		credentialsService.save(credentials);
		
		return returnStatus;
	}
	
	@RequestMapping(value="/retrieve",method=RequestMethod.POST)
	public @ResponseBody String handleRetrieveRequest(){
				
		List<Credentials> credentials = credentialsService.findAll();
		
		JSONObject responseDetailsJson = new JSONObject();
	    JSONArray jsonArray = new JSONArray();

	    for (int i = 0; i < credentials.size(); i++)
	    {
	      JSONObject formDetailsJson = new JSONObject();
	      formDetailsJson.put("username", credentials.get(i).getUsername());
	      formDetailsJson.put("password", credentials.get(i).getPassword());

	      jsonArray.add(formDetailsJson);
	    }
	    responseDetailsJson.put("credentials", jsonArray);
	    
	    return responseDetailsJson.toString();
		
	}
}

I will post the the UI related stuff(JSP) in the next tutorial to call the controller.

Happy Coding 🙂

Advertisements

2 thoughts on “Spring Integration with JPA/Hibernate using maven – I

    1. Hi Mandeep,

      I went thru the post and found no persistence.xml file there, may be i forgot to write up in the post, will post the persistence.xml soon in the same post. thanks for finding the issue.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s