Primefaces 5 example

Here is an example on how to use jsf framework to develop a fully blown JavaEE application. when it comes to jsf all should know its a specification from sun and has been implemented by lot many vendors, some of them are “PrimeFaces”, “RichFaces”, “IceFaces”. The advantage of using JSF is the UI components are directly binded to Managed bean properties(value injection). In this example i want to show how to push data to database and retrieve from database to front end. This example is implemented in “Primefaces5.1”, “Maven”, “MySql”.

<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.jsf.primefaces</groupId>
	<artifactId>PrimeFacesTutorial</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>PrimeFacesTutorial</name>
	<description>PrimeFacesTutorial</description>

	<repositories>
		<repository>
			<id>prime-repo</id>
			<name>PrimeFaces Maven Repository</name>
			<url>http://repository.primefaces.org</url>
			<layout>default</layout>
		</repository>
	</repositories>

	<properties>
		<java.version>1.6</java.version>
		<servlet.version>3.0.1</servlet.version>
		<jsf.version>2.2.4</jsf.version>
		<primefaces.version>5.1</primefaces.version>
	</properties>

	<dependencies>
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>${servlet.version}</version>
		</dependency>
		<!-- Faces Implementation -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>${jsf.version}</version>
		</dependency>
		<!-- Faces Library -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>${jsf.version}</version>
		</dependency>
		<!-- Primefaces Version 5 -->
		<dependency>
			<groupId>org.primefaces</groupId>
			<artifactId>primefaces</artifactId>
			<version>${primefaces.version}</version>
		</dependency>
		<!-- JSP Library -->
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>
		<!-- JSTL Library -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.1.2</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.9</version>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<warSourceDirectory>webapp</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
		<finalName>primefaces-tutorial</finalName>
	</build>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>PrimeFaces Web Application</display-name>

	<!-- Change to "Production" when you are ready to deploy -->
	<context-param>
		<param-name>javax.faces.PROJECT_STAGE</param-name>
		<param-value>Development</param-value>
	</context-param>

	<context-param>
		<description>State saving method: 'client' or 'server' (=default). See
			JSF Specification 2.5.2</description>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
		<param-value>client</param-value>
	</context-param>

	<context-param>
		<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
		<param-value>resources.application</param-value>
	</context-param>

	<!-- Welcome page -->
	<welcome-file-list>
		<welcome-file>login.xhtml</welcome-file>
	</welcome-file-list>

	<!-- JSF mapping -->
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map these files with JSF -->
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.jsf</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.faces</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>

</web-app>

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">
	

</faces-config>

Once done with our configuration files let us write the page from which the operations are done.
login.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:p="http://primefaces.org/ui">

<h:head>
	<h:outputStylesheet name="css/custom-styles.css" />
</h:head>
<body>
	<h:form>
		<p:panelGrid columns="2">
			<p:outputLabel value="FirstName"></p:outputLabel>
			<p:inputText value="#{loginBean.firstName}"></p:inputText>

			<p:outputLabel value="LastName"></p:outputLabel>
			<p:inputText value="#{loginBean.lastName}"></p:inputText>

			<p:outputLabel value="Email"></p:outputLabel>
			<p:inputText value="#{loginBean.emailText}"></p:inputText>

			<p:outputLabel value="Password"></p:outputLabel>
			<p:password value="#{loginBean.password}"></p:password>

			<p:commandButton action="#{loginBean.saveValues()}" value="Submit"></p:commandButton>
		</p:panelGrid>

		<p:dataTable var="loginBean" value="#{loginBean.loginBeans}">
			<p:column headerText="First Name">
				<h:outputText value="#{loginBean.firstName}" />
			</p:column>

			<p:column headerText="Last Name">
				<h:outputText value="#{loginBean.lastName}" />
			</p:column>

			<p:column headerText="Email Id">
				<h:outputText value="#{loginBean.emailText}" />
			</p:column>

			<p:column headerText="Password">
				<h:outputText value="#{loginBean.password}" />
			</p:column>
		</p:dataTable>
	</h:form>

</body>
</html>

let us write a DTO in which we hold the data.

/**
 * 
 */
package com.spark.jsf.vo;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

/**
 * @author Sony
 *
 */
@ManagedBean(name="loginVO")
@SessionScoped
public class LoginBeanVO {

	private String firstName;
	private String lastName;
	private String emailText;
	private String password;
	/**
	 * @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 emailText
	 */
	public String getEmailText() {
		return emailText;
	}
	/**
	 * @param emailText the emailText to set
	 */
	public void setEmailText(String emailText) {
		this.emailText = emailText;
	}
	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}
	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}
	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((emailText == null) ? 0 : emailText.hashCode());
		result = prime * result
				+ ((firstName == null) ? 0 : firstName.hashCode());
		result = prime * result
				+ ((lastName == null) ? 0 : lastName.hashCode());
		result = prime * result
				+ ((password == null) ? 0 : password.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 (getClass() != obj.getClass())
			return false;
		LoginBeanVO other = (LoginBeanVO) obj;
		if (emailText == null) {
			if (other.emailText != null)
				return false;
		} else if (!emailText.equals(other.emailText))
			return false;
		if (firstName == null) {
			if (other.firstName != null)
				return false;
		} else if (!firstName.equals(other.firstName))
			return false;
		if (lastName == null) {
			if (other.lastName != null)
				return false;
		} else if (!lastName.equals(other.lastName))
			return false;
		if (password == null) {
			if (other.password != null)
				return false;
		} else if (!password.equals(other.password))
			return false;
		return true;
	}
	
	
}

Here comes the major part of our code, its our backing bean which controls our jsf page. There are lot many concepts involved in the below code, we achieve dependency injection using @ManagedProperty annotation in the below code we have injected the dao and dto objects to backing bean using @ManagedProperty annotation , also we used ExternalContext object to redirect to the jsf page from managed bean.

/**
 * 
 */
package com.spark.jsf.managed.beans;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.primefaces.context.RequestContext;

import com.spark.jsf.dao.impl.LoginSaveDAOImpl;
import com.spark.jsf.vo.LoginBeanVO;
import com.spark.security.EncryptPassword;

/**
 * @author Sony
 *
 */
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean {

	private String firstName;
	private String lastName;
	private String emailText;
	private String password;
	private List<LoginBeanVO> loginBeans = new ArrayList<LoginBeanVO>();

	@ManagedProperty(value = "#{loginVO}")
	private LoginBeanVO loginBeanVO;

	@ManagedProperty(value = "#{loginSaveDao}")
	private LoginSaveDAOImpl loginSaveDAOImpl;

	/**
	 * @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 emailText
	 */
	public String getEmailText() {
		return emailText;
	}

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

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

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

	/**
	 * @return the loginSaveDAOImpl
	 */
	public LoginSaveDAOImpl getLoginSaveDAOImpl() {
		return loginSaveDAOImpl;
	}

	/**
	 * @param loginSaveDAOImpl
	 *            the loginSaveDAOImpl to set
	 */
	public void setLoginSaveDAOImpl(LoginSaveDAOImpl loginSaveDAOImpl) {
		this.loginSaveDAOImpl = loginSaveDAOImpl;
	}

	/**
	 * @return the loginBeanVO
	 */
	public LoginBeanVO getLoginBeanVO() {
		return loginBeanVO;
	}

	/**
	 * @param loginBeanVO
	 *            the loginBeanVO to set
	 */
	public void setLoginBeanVO(LoginBeanVO loginBeanVO) {
		this.loginBeanVO = loginBeanVO;
	}

	/**
	 * @return the loginBeans
	 */
	public List<LoginBeanVO> getLoginBeans() {
		return loginBeans;
	}

	/**
	 * @param loginBeans the loginBeans to set
	 */
	public void setLoginBeans(List<LoginBeanVO> loginBeans) {
		this.loginBeans = loginBeans;
	}
	
	@PostConstruct
	public void getLoginDetails(){
		
		loginBeans = loginSaveDAOImpl.getLoginBeans();
	}

	public void saveValues() {

		loginBeanVO.setFirstName(firstName);
		loginBeanVO.setLastName(lastName);
		loginBeanVO.setEmailText(emailText);
		EncryptPassword encryptPassword = new EncryptPassword("");
		String encryptedPassword = encryptPassword.encrypt(password);

		loginBeanVO.setPassword(encryptedPassword);
		boolean status = loginSaveDAOImpl.saveCredentialsToDatabase(loginBeanVO);
		
		if(status){
			FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "Info", "User details saved successfully !");
			RequestContext.getCurrentInstance().showMessageInDialog(facesMessage);
			populateLoginBeanList();
			ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
		    try {
				ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			FacesMessage facesMessage = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Failed to Save user, might be user with same email id already exist !");
			RequestContext.getCurrentInstance().showMessageInDialog(facesMessage);
		}
		
	}
	
	public void populateLoginBeanList(){
		loginBeans = loginSaveDAOImpl.getLoginBeans();
	}

}

here our dao layer logic.

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

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;

import com.spark.jsf.db.DBUtil;
import com.spark.jsf.vo.LoginBeanVO;

/**
 * @author Sony
 *
 */
@ManagedBean(name= "loginSaveDao")
@SessionScoped
public class LoginSaveDAOImpl {

	List<LoginBeanVO> loginBeanVOs;
	
	public boolean saveCredentialsToDatabase(LoginBeanVO loginBeanVO) {
		boolean status = false;
		System.out.println(loginBeanVO.getFirstName() + "  "
				+ loginBeanVO.getLastName() + "  " + loginBeanVO.getPassword());
		Connection connection = DBUtil.getDBConnection();
		System.out.println("Got the connection object: " + connection);
		String sql = "insert into login(first_name,last_name,email_id,password) values(?,?,?,?)";
		if (!checkUserWithEmailExist(connection, loginBeanVO.getEmailText())) {
			try {
				PreparedStatement preparedStatement = connection
						.prepareStatement(sql);
				preparedStatement.setString(1, loginBeanVO.getFirstName());
				preparedStatement.setString(2, loginBeanVO.getLastName());
				preparedStatement.setString(3, loginBeanVO.getEmailText());
				preparedStatement.setString(4, loginBeanVO.getPassword());
				preparedStatement.execute();
				System.out.println("--------------- Values Saved to Database ---------------");
				status = true;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else {
			System.out
					.println("------------ user already exist with the same email id ---------------");
			status = false;
		}
		return status;
	}

	private boolean checkUserWithEmailExist(Connection connection,
			String emailText) {
		String sql = "select * from login where email_id = ?";
		boolean userExist = false;
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			preparedStatement.setString(1, emailText);
			ResultSet resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				userExist = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return userExist;
	}
	
	public List<LoginBeanVO> getLoginBeans(){
		loginBeanVOs = new ArrayList<LoginBeanVO>();
		String sql = "select * from login";
		Connection connection = DBUtil.getDBConnection();
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(sql);
			ResultSet resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				LoginBeanVO beanVO = new LoginBeanVO();
				beanVO.setFirstName(resultSet.getString("first_name"));
				beanVO.setLastName((resultSet.getString("last_name")));
				beanVO.setEmailText((resultSet.getString("email_id")));
				beanVO.setPassword((resultSet.getString("password")));
				loginBeanVOs.add(beanVO);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return loginBeanVOs;
	}
}

The speciality of this example is that i have implemented the PBEWithMD5AndDES algorith for encrypting and decrypting the passwords for security purpose.
SecurityUtils.java

/**
 * 
 */
package com.spark.security;

import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

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

	public static Cipher dCipher, eCipher;
	public SecurityUtils(String helperString) {
		//b-bit salt
		byte[] salt = {(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
                (byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03};
		
		// iteration count
		int iterationCount = 19;
		try {
			// generating a temporary key, Encryptinng with DES using a pass key
			
			KeySpec keySpec = new PBEKeySpec(helperString.toCharArray(), salt, iterationCount);
			SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
			
			eCipher = Cipher.getInstance(secretKey.getAlgorithm());
			dCipher = Cipher.getInstance(secretKey.getAlgorithm());
			
			AlgorithmParameterSpec algorithmParameterSpec = new PBEParameterSpec(salt, iterationCount);
			
			eCipher.init(Cipher.ENCRYPT_MODE, secretKey, algorithmParameterSpec);
			dCipher.init(Cipher.DECRYPT_MODE, secretKey, algorithmParameterSpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

EncryptPassword.java

/**
 * 
 */
package com.spark.security;

import java.io.UnsupportedEncodingException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;

/**
 * @author Sony
 *
 */
public class EncryptPassword extends SecurityUtils{

	public EncryptPassword(String helperString) {
		super(helperString);
	}
	
	public String encrypt(String password){
		 try {
             // Encode the string into bytes using utf-8
             byte[] utf8 = password.getBytes("UTF8");
             // Encrypt
             byte[] enc = eCipher.doFinal(utf8);
             // Encode bytes to base64 to get a string
             return new sun.misc.BASE64Encoder().encode(enc);

      } catch (BadPaddingException e) {
    	  e.printStackTrace();
      } catch (IllegalBlockSizeException e) {
    	  e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
    	  e.printStackTrace();
      }
      return null;
	}
}

DecryptPassword.java

/**
 * 
 */
package com.spark.security;

/**
 * @author Sony
 *
 */
public class DecryptPassword extends SecurityUtils {

	public DecryptPassword(String helperString) {
		super(helperString);
	}

	public String decrypt(String encryptedPassword) {
		try {
			// Decode base64 to get bytes
			byte[] dec = new sun.misc.BASE64Decoder()
					.decodeBuffer(encryptedPassword);
			// Decrypt
			byte[] utf8 = dCipher.doFinal(dec);
			// Decode using utf-8
			return new String(utf8, "UTF8");
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

}

Let us have a helper class which will create a connection object and return DAO layer.

/**
 * 
 */
package com.spark.jsf.db;

import java.sql.Connection;
import java.sql.DriverManager;

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

	private static Connection connection = null;
	
	private DBUtil(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getDBConnection(){
		if(connection == null){
			return new DBUtil().getConnection();
		}else{
			return connection;
		}
	}

	/**
	 * @return the connection
	 */
	public Connection getConnection() {
		return connection;
	}

	/**
	 * @param connection the connection to set
	 */
	public  void setConnection(Connection connection) {
		this.connection = connection;
	}
	
}

finally the output is as below.

ui

Advertisements

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 🙂

Hibernate Inheritance: Table Per Class hierarchy

Hi Guys, Here i am going to discuss some of the best features of Hibernate framework. For the next few classes i am going to discuss about inheritance in Java and how to implement it in Hibernate.

Object oriented systems are majorly implemented with “is a” and “has a” relationship. Relational databases supports only “has a” relationship between two entities. Hibernate can help you map such Objects with relational tables, only thing is we need to choose certain mapping strategy based on our needs.

Table Per Class Hierarchy:
Let us consider we have a Person class and Employee class which extend from Person class

Class Person {
property firstName
property lastName
}


Class Employee extends Person{
property joiningDate
property departmentName
}

In Table per Class Hierarchy , we store all the class hierarchy in a single table. A discriminator is a key to uniquely identify the base type of the class hierarchy.i.e we store the Employee and Person related information in Person table in database.

Following are the advantages and disadvantages of Table per Class Hierarchy.
Advantage
This hierarchy offers the best performance even for in the deep hierarchy since single select may suffice.
Disadvantage
The columns for properties declared by subclasses must be declared to accept null Values, these columns cannot be declared with NOT NULL constraint.

Following is the Sql script:

DROP TABLE IF EXISTS `test`.`person`;
CREATE TABLE  `test`.`person` (
  `person_id` bigint(10) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(50) DEFAULT NULL,
  `lastname` varchar(50) DEFAULT NULL,
  `joining_date` date DEFAULT NULL,
  `department_name` varchar(50) DEFAULT NULL,
  `discriminator` varchar(20) NOT NULL,
  PRIMARY KEY (`person_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

In the following example i’ll demonstrate the mapping using hbm.xml file and next by annotation.
Person.Java

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

import java.io.Serializable;

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

	private int personId;
	private String firstName;
	private String lastName;
	
	public Person() {
		// TODO Auto-generated constructor stub
	}
	
	public Person(String firstName,String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	/**
	 * @return the personId
	 */
	public int getPersonId() {
		return personId;
	}

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

	/**
	 * @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;
	}

}

Employee.java

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

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

/**
 * @author Sony
 * 
 */
public class Employee extends Person implements Serializable {

	private Date joiningDate;
	private String departmentName;
	
	public Employee() {
		// TODO Auto-generated constructor stub
	}
	
	public Employee(String firstName,String lastName,Date joiningDate,String departmentName) {
		super(firstName,lastName);
		this.joiningDate = joiningDate;
		this.departmentName = departmentName;
	}

	/**
	 * @return the joiningDate
	 */
	public Date getJoiningDate() {
		return joiningDate;
	}

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

	/**
	 * @return the departmentName
	 */
	public String getDepartmentName() {
		return departmentName;
	}

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

}

Now lets look at hibernate.cfg.xml which allows the configuration for hibernate framework.

<?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">Password</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/Person.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

Now lets have a look at hbm file i name it as Person.hbm.xml

<?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 15 Jun, 2013 7:42:12 PM by Hibernate Tools 3.4.0.CR1 -->

<hibernate-mapping package="com.spark.hibernate.model">
    <class name="Person" table="PERSON" discriminator-value="P">
        <id name="personId" type="int">
            <column name="PERSON_ID" />
            <generator class="native" />
        </id>
        
        <discriminator column="DISCRIMINATOR" type="string" />
        <property name="firstName" type="java.lang.String">
            <column name="FIRSTNAME" />
        </property>
        <property name="lastName" type="java.lang.String">
            <column name="LASTNAME" />
        </property>
        
        <subclass name="Employee" extends="Person" discriminator-value="E">
        	<property name="joiningDate" type="date" column="joining_date"></property>
        	<property name="departmentName" type="string" column="department_name"></property>
        </subclass>
    </class>
</hibernate-mapping>

Lets have a small discussion on the above file, Note that we have only one hibernate mapping (hbm) file Person.hbm.xml. Both Person and Employee model(POJO) classes are defined within one hbm file.

tag is used to define the discriminator column.
NOTE: your discriminator tag should appear right after the id tag if not you will run into errors

tag is used to map the subclass Employee. Note that we have not used the usual tag to map Employee as it falls below in the hierarchy tree.

The discriminator-value for Person is defined as “P” and that for Employee is defined “E”, Thus, when Hibernate will persist the data for person or employee it will accordingly populate this value.

Lets have a look at our main class to run:
Main.java

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

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.spark.hibernate.model.Employee;
import com.spark.hibernate.model.Person;
import com.spark.hibernate.util.HibernateUtil;

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

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

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		session.beginTransaction();
		
		Person person = new Person("James","Gosling");
		session.save(person);
		
		Employee employee = new Employee("Bill","Gates",new Date(), "Java Development");
		session.save(employee);
		
		session.getTransaction().commit();
		session.close();
		sessionFactory.close();
		
	}

}

We used a helper class to get the SessionFactory Object of Hibernate, so here it is:

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

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

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

	private static SessionFactory sessionFactory;
	
	public static SessionFactory getSessionFactory(){
		
		sessionFactory = new Configuration().configure().buildSessionFactory();
		return sessionFactory;
	}
}

Finally the output should look like the following

Table_Per_Class_Query_OP

Table_Per_Class

Happy Coding 🙂

Web services using JAXB

Hi Guys here is my brief post on how to develop web services using jaxb notation.

The Java Architecture for XML Binding API (JAXB) makes it easy to access XML documents from applications written in the Java programming language. JAXB is an alternative to using a SAX or DOM parser to access the data in an XML document. When you access an XML document with JAXB, first you bind the schema for the XML document into a set of Java classes that represents the schema. Then you unmarshal the XML document. Unmarshalling a document means creating a tree of content objects that represents the content and organization of the document.

You can also use JAXB to build an XML document. To build an XML document with JAXB, you first bind the schema for the XML document you want to build. Then you create a content tree. Lastly, you marshal the content tree into an XML document.

The following diagram, from Java Architecture for XML Binding API, shows the processes both for accessing and for building XML documents from Java applications.


Working with JAXB is easy, just annotate object with JAXB annotation, later use jaxbMarshaller.marshal() or jaxbMarshaller.unmarshal() to do the object / XML conversion.
No extra jaxb libraries are required if you are using JDK1.6 or above, because JAXB is bundled in JDK 1.6.
Note
For JDK < 1.6, download JAXB from here and put “jaxb-api.jar” and “jaxb-impl.jar” on your project classpath.

now lets see how to code with “jaxb”

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

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author Pavan Mantha
 * 
 */
@SuppressWarnings("serial")
@XmlRootElement
public class Customer implements Serializable {

	private int id;
	private String firstName;
	private String lastName;
	private String designation;
	private String phoneNumber;

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

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

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

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

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

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

	/**
	 * @return the designation
	 */
	public String getDesignation() {
		return designation;
	}

	/**
	 * @param designation
	 *            the designation to set
	 */
	@XmlElement
	public void setDesignation(String designation) {
		this.designation = designation;
	}

	/**
	 * @return the phoneNumber
	 */
	public String getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber
	 *            the phoneNumber to set
	 */
	@XmlElement
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

}

now its time to code jaxb marshaller,

/**
 * 
 */
package com.spark.jaxb.marshaller;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.spark.jaxb.model.Customer;

/**
 * @author Pavan Mantha
 * 
 */
public class JaxbMarshaller {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Customer customer = new Customer();
		customer.setId(100);
		customer.setFirstName("Pavan");
		customer.setLastName("Mantha");
		customer.setDesignation("SoftwareEngineer");
		customer.setPhoneNumber("123-4567-890");

		try {

			File file = new File("C:\\customer.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

			// output pretty printed
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			jaxbMarshaller.marshal(customer, file);
			jaxbMarshaller.marshal(customer, System.out);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

and unmarshaller as below.

/**
 * 
 */
package com.spark.jaxb.unmarshaller;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.spark.jaxb.model.Customer;

/**
 * @author Pavan Mantha
 * 
 */
public class JaxbUnmarshaller {

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

			File file = new File("C:\\customer.xml");
			JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
			System.out.println(customer);

		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

Happy Coding 🙂

Consuming web service using Spring 3.x

Hi guys, Here i am going to demonstrate how to consume web service using spring framework.Consuming web services with Spring framework is amazingly easy. It avoids the need of creating client side stubs during compile time and does the same at run time. A typical web service client can be configured as shown below-

inorder to get the spring capability for webservice please add the following dependencies to pom.xml as 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.webservice</groupId>
  <artifactId>SpringWebService</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringWebService</name>
  <description>SpringWebService</description>
  
  <dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-core</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-context-support</artifactId>
  		<version>3.1.1.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-beans</artifactId>
  		<version>3.1.1.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework.ws</groupId>
  		<artifactId>spring-ws-core</artifactId>
  		<version>2.1.1.RELEASE</version>
  	</dependency>
  </dependencies>
</project>

please configure your applicationContext.xml as below-

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

	<bean id="myWebService"
		class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">
		<property name="serviceInterface" value="com.spark.webservice.TemperatureConverter" />
		<property name="wsdlDocumentUrl" value="http://localhost:8080/JBossWebServices?wsdl" />
		<property name="namespaceUri" value="http://impl.webservice.spark.com/" />
		<property name="serviceName" value="TemperatureConverter" />
		<property name="portName" value="TemperatureConverterImplPort" />
	</bean>

</beans>

Where serviceInterface is the business interface that clients will use for invoking service methods. wsdlDocumentUrl is the URL for the published WSDL file. Spring will download WSDL from the given URL and generate the client side stubs when it creates the bean usually during application start up. namespaceUri corresponds to the targetNamespace in the .wsdl file. serviceName corresponds to the service name in the .wsdl file. portName corresponds to the port name in the .wsdl file.

Note Please refer to my previous port to get the wsdl file.

Now accessing web service pretty easy, just get the bean from Spring context and use that to invoke methods-

/**
 * 
 */
package com.spark.spring.webservice.client;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spark.webservice.TemperatureConverter;

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

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		TemperatureConverter converter = (TemperatureConverter)applicationContext.getBean("myWebService");
		System.out.println(converter.convertCelsiusToFahrenheit(42.0));
	}

}

inorder to use the service we need to create the service interface type as below –

/**
 * 
 */
package com.spark.webservice;

import javax.jws.WebMethod;
import javax.jws.WebService;

/**
 * @author Sony
 *
 */
@SuppressWarnings("restriction")
@WebService
public interface TemperatureConverter {

	@WebMethod
	public double convertCelsiusToFahrenheit(double value);
	@WebMethod
	public double convertFahrenheitToCelsius(double value);
}

Thats it now run the main method and get the result.
Note: the service should be up and running in the server.

Happy Coding 🙂

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 🙂