Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

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.

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