Tuesday, July 2, 2013

Spring 3 + Hibernate 4 integration

Today I would like to demonstrate how to use Hibernate in Spring framework to do the data manipulation works in MySQL database.I will use spring mvc 3, hibernate 4 frameworks and spring annotation for bean creation and also generic dao class for data manipulation works.

Step 1: Mysql employee Table Creation.

 This is the employee table structure.

CREATE TABLE `employee` (                                
  `ID` BIGINT(20) NOT NULL AUTO_INCREMENT,               
  `ADDRESS` VARCHAR(255) NOT NULL,                       
  `CONTACT_NUMBER` VARCHAR(30) NOT NULL,                 
  `NAME` VARCHAR(20) NOT NULL,                                                  
   PRIMARY KEY (`ID`),                                    
   UNIQUE KEY `ID` (`ID`)                                 
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 

Now create a Maven web project using eclipse or NetBeans.

Step 2: Pom.xml file configuration




    4.0.0
    com.sasika.pos
    Pos_server
    1.0-SNAPSHOT
    war
    Pos_server
    http://maven.apache.org

    
        3.2.1.RELEASE
        3.1.2.RELEASE
    

    
        
         
        
            org.springframework
            spring-web
            ${org.springframework.version}
        
        
            org.springframework
            spring-webmvc
            ${org.springframework.version}
        
        
            org.springframework
            spring-context
            ${org.springframework.version}
        
        
            org.springframework
            spring-orm
            ${org.springframework.version}
        
        
            org.springframework
            spring-test
            ${org.springframework.version}
        
        
            org.springframework
            spring-jdbc
            ${org.springframework.version}
        
        
        

        
            org.apache.cxf
            cxf-api
            2.6.0
            compile
        

        
            org.apache.cxf
            cxf-rt-frontend-jaxws
            2.6.0
            compile
        

        
            org.apache.cxf
            cxf-rt-transports-http
            2.6.0
            compile
        


        
            javax.servlet
            javax.servlet-api
            3.0.1
        
        
        
        
        
            org.hibernate
            hibernate-core
            4.1.12.Final
        
        
            org.hibernate
            hibernate-validator
            4.2.0.Final
        

        
            junit
            junit
            4.8.2
        

        
            mysql
            mysql-connector-java
            5.1.9
        
        
            javax.servlet
            jstl
            1.2
        
    

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                2.3.2
                
                    1.5
                    1.5
                
            
            
                org.apache.maven.plugins
                maven-war-plugin
                2.1.1
                
                    false
                
            
        
    



Some of dependencies not need for this application (like Apache CXF for webservices), but I will put it because this demonstration will be continue.

Step 3: Hibernate annotation class for data model

we have to define Employee.java class and annotate it to data model.

package com.sasika.pos.entity;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;


@Entity
@Table(name = "employee", catalog = "erp_pos")
public class Employee implements java.io.Serializable {

    private Long id;
    private String address;
    private String name;
    private String contactNumber;

    public Employee() {
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    public Long getId() {
        return this.id;
    }

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

    @Column(name = "ADDRESS", nullable = false)
    public String getAddress() {
        return this.address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Column(name = "NAME", nullable = false, length = 20)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "CONTACT_NUMBER", nullable = false, length = 30)
    public String getContactNumber() {
        return this.contactNumber;
    }

    public void setContactNumber(String contactNumber) {
        this.contactNumber = contactNumber;
    }

}

Step 4: Generic Dao for data access

We can use generic DAO class for common methods such as save, update, delete, findAll.. which are required in every DAO class. We will create Genericdao and GenericDaoimpl for common methods.



public interface GenericDao <e extends serializable > {

    List <e> findAll();
    E findById(Long id);
    void saveOrUpdate(E e);
    void delete(E e);
    List <e> findByCriteria(Criterion criterion);
}


package com.sasika.pos.generic.dao;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.Serializable;
import java.util.List;

public abstract class GenericDaoImpl <e extends  serializable > implements GenericDao <e> {

    private Class<e> entityClass;

    protected GenericDaoImpl(Class<e> entityClass) {
        this.entityClass = entityClass;
    }

    @Autowired
    private SessionFactory sessionFactory;

    public Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public List<e> findAll() {
        return (List<e>) getCurrentSession().createQuery("from " + entityClass.getSimpleName()).list();
    }
    
    @Override
    public E findById(Long id) {
        return (E) getCurrentSession().get(entityClass, id);
    }

    @Override
    public void saveOrUpdate(E e) {
        getCurrentSession().saveOrUpdate(e);
    }

    @Override
    public void delete(E e) {
        getCurrentSession().delete(e);
    }

    @Override
    public List<e> findByCriteria(Criterion criterion) {
        Criteria criteria = getCurrentSession().createCriteria(entityClass);
        criteria.add(criterion);
        return criteria.list();
    }
}

Step 5:Bo and Dao Implementation

Employee data access object

A Employee DAO interface and implementation, the dao implementation class extends  Generic Dao implementation class


package com.sasika.pos.employee.dao;

import com.sasika.pos.entity.Employee;
import com.sasika.pos.generic.dao.GenericDao;

public interface EmployeeDao extends GenericDao<employee<{
    
}


package com.sasika.pos.employee.dao;

import com.sasika.pos.entity.Employee;
import com.sasika.pos.generic.dao.GenericDaoImpl;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDaoImpl extends GenericDaoImpl<employee> implements EmployeeDao{

    public EmployeeDaoImpl() {
        super(Employee.class);
    }
    
}


There is a @Repository annotation and it Indicates DAO component in the persistence layer.

Employee Business Object(Bo)
Employee business object (BO) interface and implementation, it’s used to handle the project’s business function.
package com.sasika.pos.employee.bo;

import com.sasika.pos.entity.Employee;
import java.util.List;

public interface EmployeeBo {
    
    public String saveOrUpdateEmployee(Employee employee);

    public List<employee> findAllEmployee();
    
    public void deleteEmployee(Employee employee);
    
}


package com.sasika.pos.employee.bo;

import com.sasika.pos.employee.dao.EmployeeDao;
import com.sasika.pos.entity.Employee;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class EmployeeBoImpl implements EmployeeBo {
    
    @Autowired
    private EmployeeDao employeeDao;
    
    @Transactional
    public String saveOrUpdateEmployee(Employee employee) {
        try {
            if (employee.getId() == 0) {
                employee.setId(null);
            }
            employeeDao.saveOrUpdate(employee);
        } catch (Exception e) {
            return "Error";
        }
        return "success";
    }
    
    public List<employee> findAllEmployee() {
        return employeeDao.findAll();
    }

    @Transactional
    public void deleteEmployee(Employee employee) {
        employeeDao.delete(employee);
    }
}


There is a @ Service annotation and it Indicates a Service component in the business layer.

Step 6: 5. Resource Configuration


hibernateContext.Xml configuration
Create a HibernateContext file for Data source, transaction and hibernate session factory beans, put it under “resources/config/spring” folder


    
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/erp_pos"/>
        <property name="username" value="username"/>
        <property name="password" value="password"/>
    

    
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.sasika.pos.entity"/>
        
            
                org.hibernate.dialect.MySQLDialect
                update
            
        
    
  
    
        <property name="sessionFactory" ref="sessionFactory"/>
    





Application Context file configuration


    
    <context:component-scan base-package="com.sasika.pos"/>
    <tx:annotation-driven transaction-manager="transactionManager"/>

    
    <import resource="classes/config/spring/hibernateContext.xml"/>
    



Transaction will be handle by using annotation.

Web xml Configuration

  
    
        org.springframework.web.context.ContextLoaderListener
    

    
        
            30
        
    




Now all the configurations finished. We can test this application using Junit.I will show how to test this using junit in next post.

 I will show you how to integrate this project with apache CXF web service in my next few post as well.

Monday, June 3, 2013

How to use and advantages of Spring RMI

My current project is java RMI (remote method invocation) project and we are using spring as main framework. There are lots of advantages when you use spring framework for RMI. Before I go father I will show you RMI example without using spring framework.

Create an interface name Hello.java and declare sayHello method without body as per the requirement of a simple Hello RMI application.


import java.rmi.Remote;

public interface Hello extends Remote{
    public String sayHello();
}

The next step is to implement the interface so define a class.

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class HelloImpl extends UnicastRemoteObject implements Hello {

    protected HelloImpl() throws RemoteException {
        super();
    }

    @Override
    public String sayHello() {
        System.out.println("Hello");
        return "Hello";
    }
}

Define the Server side class.

import java.rmi.Naming;
public class HelloServer {

    public HelloServer() {
        try {
            Hello h = new HelloImpl();
            Naming.rebind("rmi://localhost:1099/HelloService", h);
        } catch (Exception e) {
            System.out.println("Exception is : " + e);
        }
    }
    
    public static void main(String[] args) {
        new HelloServer();
    }
}

Now server side code is over. Define the Client side class to access sayHello method.
import java.rmi.Naming;

public class HelloClient {
    public static void main(String[] args) {
        try {
            Hello h = (Hello) Naming.lookup("//127.0.0.1:1099/HelloService");
            System.out.println("Say : " + h.sayHello());
        } catch (Exception ex) {
            System.out.println("Error " + ex);
        } 
            
    }
}

These are the steps of RMI example without spring. Now check how Spring framework can implement same example.

package com.sasika.hello;

public interface Hello{
    public String sayHello();
}

You don’t need to extend Hello java interface from Remote Interface. You don’t need to extend UnicastRemoteObject as well.

package com.sasika.hello;
public class HelloImpl implements Hello {

    @Override
    public String sayHello() {
        System.out.println("Hello");
        return "Hello";
    }
}
We can export the interface of our HelloImpl object as RMI object. To do that we can use spring RmiServiceExporter. Next code sample shows how to export our business logic(HelloImpl) to RMI service using spring.
For more detail visit: http://static.springsource.org/spring/docs/2.0.8/reference/remoting.html



   
        
   

   
   

   
   


That’s all for server side. Now look at the client side code. We need to write SpringConfiguration.xml for access Rmi service.





        
        




public class HelloClient {
    public void callHello() {
        try {
            ApplicationContext ctx =  new ClassPathXmlApplicationContext("classpath:com/sasika/hello/SpringConfiguration.xml");
            Hello h = (UserRolePermissionBo) ctx.getBean("helloBean");
            System.out.println("Say : " + h.sayHello());
        } catch (Exception ex) {
            System.out.println("Error " + ex);
        } 
            
    }
}


This is how we develop RMI project with spring. So what are the advantages of using spring RMI.

There are few advantages. One is you don’t need to extend any RMI related Interfaces. So you can concentrate your application business logic rather than RMI specific codes. When you don’t extend RMI related Interfaces your application can export any other services without changing your existing code.

For example if you need to write Hello web service, you can write another class (HelloWs) and call existing Hello java class method. You don’t need to QA for existing code.Same as you can write web client or any other service without changing existing code.

This will improve your system Flexibility, Maintainability, and Extensibility.

In here with spring, RMI specific codes move into xml file. This reduces complexity of codes. Hiding complexity is another advantage.

Wednesday, May 8, 2013

Design patterns can save your day


Last month I was working on inventory control system with my team members. We were developing it using “weighted average” inventory method on SRS prepared BA’s. After few week of development requirements change as no surprise. The management want to develop it’s using both “weighted average” and “first in first out(FIFO)” methods.

So we discussed how to change our design for these new requirements. We were using spring as MVC framework and JPA for ORM. It is client (Java Swing) server application using RMI. After few hours of discussion we decided to write InventoryManagerDao interface and two implementation class called InventoryManagerFifoDaoImpl and InventoryManagerWavgDaoImpl.(Initially we decided to write abstract class but these two inventory methods(FIFO and weighted average) does not have any common methods) 

Our design looks like this


This design looks fine for us. But we had another problem with this design.When we were using this design we have to check which inventory method initially configured. We have to check it using if condition and get the appropriate inventory manager object from few areas (Sales Invoice, GRN, Returns…). It is code duplication. So we decided to give this object creation responsibility to some other class called InventoryHandle.

Now design looks like this.


This design looks maintainable and extensible. Few days later we found that this is almost a design pattern. It is a Factory method pattern.

 

I have read Head First Design Patterns ebook once and I knew few design patterns. But I did not memorize it. We need to know how to apply design pattern with real scenarios. So I decide to follow these design patterns seriously and try to understand and memorize (of course how to apply). Because design patterns can save our day.

Friday, April 19, 2013

Why do we need java frameworks?


What is core java and advanced java?
Before we start talking about java framework, we should know about core and advance java.
Core java comes with java 'Standard Edition' and it has to do with the basic package of Java objects that are typically used for general desktop applications.
Where as advance java is specialisation in some domain, such as networking, web, DCOM or database handling.


What is Frameworks?
Framework is set of reusable software program that forms the basis for an application. Frameworks helps the programmers to build the application quickly. Earlier it was very hard to develop complex web applications. Now it’s very easy to develop such application using different kinds of frameworks such as Struts, Struts 2, Hibernate,  JSF, Tapestry, JUnit, Log4j, Spring etc.
http://www.roseindia.net/frameworks/

Example of Java frameworks
MVC frameworks : Spring
ORM frameworks : Hibernate, Oracle TopLink, iBATIS
Presentation layer frameworks : Struts, JSF, Apache Wicket

Example of Framework usage
I will show how JDBC that inserts data into the database and how simply do it using java frameworks(Spring & Hibernate).

Consider there is a Customer table in your database.

CREATE TABLE `customer` (                              
             `CUSTOMER_ID` BIGINT(20) NOT NULL AUTO_INCREMENT,    
             `NAME` VARCHAR(45) NOT NULL,                          
              PRIMARY KEY (`CUSTOMER_ID`),                          
              UNIQUE KEY `CUSTOMER_ID` (`CUSTOMER_ID`)              
              )

JDBC Insert customer method using PreparedStatement

private void insertCustomerIntoTable(Customer customer) throws SQLException {
  Connection dbConnection = null;
  PreparedStatement preparedStatement = null;
  String insertTableSQL = "INSERT INTO CUSTOMER ( CUSTOMER_ID, NAME) VALUES (?,?)";
  try {
   dbConnection = getDBConnection();
   preparedStatement = dbConnection.prepareStatement(insertTableSQL);
   preparedStatement.setInt(1, customer.getCustomerId());
   preparedStatement.setString(2, customer.getName());
   preparedStatement.executeUpdate();

   } catch (SQLException e) {
    System.out.println(e.getMessage());
   } finally {
    if (preparedStatement != null) {
    preparedStatement.close();
   }
    if (dbConnection != null) {
    dbConnection.close();
   }
  }
  }

We have to code this much no of line to achieve our goal.(I do not show the database connection method and Customer class with getters and setters )

Now when we configure this project with spring mvc and hibernate frameworks code is simplify like this

@Transactional
private void insertCustomerIntoTable(Customer customer){
      session.save(customer);
}

That’s it. That’s what all we need to do. @Transactional annotation will handle the transactional part in database access and hibernate session’s save method will insert customer data into table.If anything goes  wrong and Exception throws,this method will rollback transaction.
(to achieve this we need to do some configurations like Datasource, HibernateSessionFactory, TransactionManager spring beans)

There are so many example like this,when you develop application using java frameworks.Main advantage is we can concentrate our application business logic rather than handling data access common boilerplate code.
Other than this some of advantage of frameworks are
  • Hiding complexity
  • Increase performance
  • Modularity
  • Flexibility, Maintainability, and Extensibility