Spring Hibernate integration using Java project

Spring Hibernate integration using Java project

Here you will see show to integrate Spring with Hibernate using standalone java project. We will integrate Spring with Hibernate and use Hibernate for all database related operation and Spring as service to pass required command to database layer and result will be shown on console.

Tools used:

  • Eclipse ( We are using eclipse Kepler download from here)
  • Install JBoss tools in eclipse. If you are not sure how to install JBoss in eclipse please user this URL:Install JBoss tools in eclipse
  • MySQL data base (Install MySQL Community Server (GPL) version in your system : MySQL Community Server). We are using version 5.6
  • Hibernate 4.3.5.Final
  • Maven 3.0.4

Steps:

1. Create table in MySQL data base script:

CREATE TABLE Person ( 
    First_Name  varchar(50) NULL,
    Last_Name   varchar(25) NULL,
    City        varchar(25) NULL,
    Zip         varchar(25) NULL,
    State       varchar(25) NULL,
    id          int(11) NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id)
    )

GO

2. Create Maven project name: SpringHibernate (If you are not sure how to create Maven project in eclipse please use this tutorial)

3. Final project structure:
Spring Hibernate integration using Java project

Note: if you are using eclipse project please include below jars in your class path:

Spring Hibernate integration using Java project

 

4. Hibernate configuration:

5. Hibernate configuration files:

  • Hibernate.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>
 
    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
     </property>
 
    <property name="mappingResources">
    <list>
           <value>hibernate/Person.hbm.xml</value>
    </list>
      </property>   
 
    </bean>
</beans>
  • 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 Jun 1, 2014 9:01:17 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.javahonk.model.Person" table="person" catalog="javahonk">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="string">
            <column name="First_Name" length="50" />
        </property>
        <property name="lastName" type="string">
            <column name="Last_Name" length="25" />
        </property>
        <property name="city" type="string">
            <column name="City" length="25" />
        </property>
        <property name="zip" type="string">
            <column name="Zip" length="25" />
        </property>
        <property name="state" type="string">
            <column name="State" length="25" />
        </property>
    </class>
</hibernate-mapping>

6. Properties File:

  • database.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/javahonk
jdbc.username=root
jdbc.password=admin

7. Spring configuration file:

  • applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
    <import resource="../spring/DataSource.xml"/>
    <import resource="../hibernate/Hibernate.xml"/> 
    <import resource="../spring/Person.xml"/>
 
</beans>
  • DataSource.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
<bean 
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>properties/database.properties</value>
    </property>
</bean>
 
<bean id="dataSource" 
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>
 
</beans>
  • Person.xml
<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
 
   <bean id="personService" class="com.javahonk.service.PersonServiceImpl" >
        <property name="personDAO" ref="personDAO" />
   </bean>
 
   <bean id="personDAO" class="com.javahonk.dao.PersonDAOImpl" >
        <property name="sessionFactory" ref="sessionFactory"></property>
   </bean>

    <tx:annotation-driven />
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
 
</beans>

8. Hibernate Model class Person.java

package com.javahonk.model;

// Generated Jun 1, 2014 9:01:17 AM by Hibernate Tools 3.4.0.CR1

/**
 * Person generated by hbm2java
 */
public class Person implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private Integer id;
    private String firstName;
    private String lastName;
    private String city;
    private String zip;
    private String state;

    public Person() {
    }

    public Person(String firstName, String lastName, String city, String zip,
            String state) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.city = city;
        this.zip = zip;
        this.state = state;
    }

    public Integer getId() {
        return this.id;
    }

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

    public String getFirstName() {
        return this.firstName;
    }

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

    public String getLastName() {
        return this.lastName;
    }

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

    public String getCity() {
        return this.city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getZip() {
        return this.zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }

    public String getState() {
        return this.state;
    }

    public void setState(String state) {
        this.state = state;
    }

}

9. Hibernate DAO class:

  • PersonDAO.java
package com.javahonk.dao;

import java.util.List;

import com.javahonk.model.Person;

public interface PersonDAO {
    
    void insertPerson(Person person);
    
    List<Person> findAllPerson();
    
    void updatePerson(Integer personId);
    
    void deletePerson(Integer personId);

}

  • PersonDAOImpl.java
package com.javahonk.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import com.javahonk.model.Person;

@Transactional
public class PersonDAOImpl implements PersonDAO{
    
    SessionFactory sessionFactory;
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    public void insertPerson(Person person) {
        Session session = sessionFactory.getCurrentSession();
        session.save(person);
        
    }   

    public void updatePerson(Integer personId) {
        
        Person person = new Person();
        person.setId(personId);
        person.setCity("NY");
        person.setLastName("Honk");
        person.setState("NY");
        person.setZip("12345"); 
        person.setFirstName("New Update Java"); 
        this.sessionFactory.getCurrentSession().update(person);     
        
    }
    
    public List<Person> findAllPerson() {
        List<Person> list = (List<Person>)this.sessionFactory
                .getCurrentSession().createQuery("from Person")
                .list();        
        return list;
        
    }
    
    public void deletePerson(Integer personId) {
        
        Person person2 = (Person) sessionFactory.getCurrentSession()
                .get(Person.class, personId);
        if (null != person2) {
            this.sessionFactory.getCurrentSession().delete(person2);
        }
        
    }   

}

10. Spring service class:

  • PersonService.java
package com.javahonk.service;


import java.util.List;

import com.javahonk.model.Person;

public interface PersonService {
    
    void insertPerson(Person person);
    
    List<Person> findAllPerson();
    
    void updatePerson(Integer personId);
    
    void deletePerson(Integer personId);
    

}

  • PersonServiceImpl.java
package com.javahonk.service;


import java.util.List;

import com.javahonk.dao.PersonDAO;
import com.javahonk.model.Person;

public class PersonServiceImpl implements PersonService{
    
    PersonDAO personDAO;

    public void deletePerson(Integer personId) {
        personDAO.deletePerson(personId);
        
    }

    public List<Person> findAllPerson() {
        return personDAO.findAllPerson();
    }

    public void insertPerson(Person person) {
        personDAO.insertPerson(person);
        
    }

    public PersonDAO getPersonDAO() {
        return personDAO;
    }

    public void setPersonDAO(PersonDAO personDAO) {
        this.personDAO = personDAO;
    }

    public void updatePerson(Integer personId) {
        personDAO.updatePerson(personId);
        
    }
    
    

}

11. Finally Test class to perform and validate all operation SpringHibernateTest.java

package com.javahonk;

import java.util.List;

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

import com.javahonk.model.Person;
import com.javahonk.service.PersonService;

public class SpringHibernateTest {
    
    public static void main(String[] args) {
        
        ApplicationContext appContext = 
                new ClassPathXmlApplicationContext(
                        "spring/applicationContext.xml");

        PersonService personService = (PersonService) appContext
                .getBean("personService");

        //Insert Person
        Person person = new Person();
        person.setCity("NY");
        person.setFirstName("Java");
        person.setLastName("Honk");
        person.setState("NY");
        person.setZip("12345");     
        personService.insertPerson(person);
        
        //Select Person     
        List<Person> listPerson = personService.findAllPerson();
        for (Person person2 : listPerson) {
            System.out.println("First Name: "+person2.getFirstName()
                    +" Last Name: "+person2.getLastName()
                    +" City: "+person2.getCity()
                    +" State: "+person2.getState()
                    +" Zip: "+person2.getZip());
        }
        
        //Update Person
        personService.updatePerson(1);
        
        //Delete Person
        personService.deletePerson(1);
        
        ((AbstractApplicationContext)appContext).close();
        
    }
}

 

12. To run: Right click SpringHibernateTest.java –> Run As –> Java Application. You will see data insert, select , update and deleted from the table on the console as below:

3

 

download Download Project: SpringHibernate

For more information please see this Spring tutorial

That’s it Spring Hibernate integration using Java project

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *