1. Overview

This is an example of Spring Hibernate XML configuration. In this example, we try to explain how to communicate with the database using spring. In below example we have three layers:

  1. Controller
    1. The controller will accept a request from the client and prepare response using service layer. After preparing a response by service layer passes those data to the view layer. View Layer may JSP, XML, JSON.
    2. To Define Controller @Controller annotation is used.
  1. Service Layer
    1. Service layer can be defined using @Service annotation at the class level. The service layer is responsible for business logic. Service layer communicates with Database layer perform the database operation.
  1. DAO Layer
    1. DAO layer is used to perform database operations. In this example, we are using MySQL as a database. DAO layer injects SessionFactory object using that DAO Layer performs database object.

Technology Used:

  1. String 4.3.0
  2. Hibernate 4.2.11
  3. MySQL
  4. Maven 2.3.2
  5. Tomcat 7
  6. Java 8
  7. IntelljIDEA 14

2. Example

pom.xml

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springapp</groupId>
    <artifactId>spring-hibernate-xml-configuration</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>spring-hibernate-xml-configuration</name>
    <description>Spring Hibernate XML configuration</description>
    <properties>
        <spring.version>4.3.1.RELEASE</spring.version>
        <hibernate.version>4.2.11.Final</hibernate.version>
        <mysql.connector.version>5.1.31</mysql.connector.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--Transaction API-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

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

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>


    </dependencies>

    <build>
        <finalName>spring-hello-work</finalName>

        <plugins>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

EmployeeController.java

package com.springdemo.controller;

import com.springdemo.model.Employee;
import com.springdemo.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        return "createEmployee";
    }

    @RequestMapping(value = "viewEmployee", method = RequestMethod.GET)
    public String viewEmployee(ModelMap model) {
        model.addAttribute("employees", employeeService.list());
        return "viewEmployee";
    }

    @RequestMapping(value = "saveEmployee", method = RequestMethod.POST)
    public String saveEmployee(Employee employee) {
        employeeService.save(employee);
        return "redirect:viewEmployee";
    }

}

EmployeeDAO

package com.springdemo.dao;

import com.springdemo.model.Employee;

import java.util.List;


public interface EmployeeDAO {
    public void save(Employee employee);
    public List<Employee> list();
}

EmployeeDAOImpl.java

package com.springdemo.dao;

import com.springdemo.model.Employee;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Repository
@Transactional
public class EmployeeDAOImpl implements EmployeeDAO {

    @Autowired
    SessionFactory sessionFactory;

    @Override
    public void save(Employee employee) {
        sessionFactory.getCurrentSession().save(employee);
    }

    @Override
    public List<Employee> list() {
        return sessionFactory.getCurrentSession().createCriteria(Employee.class).list();
    }
}

 

Employee.java

@Entity indicate that table name refer in Java like when create HSL query.

@Table indicate that name of table which are available in database.

@ID indicate its primary key will be created in database.

@Column: column will be create in that table with same name.

here we can also pass name attribute like @Column(name=”employee_name’) so that column name(employee_name) will be create in database and we can use our favorite camel notation in java(employeeName).

package com.springdemo.model;

import javax.persistence.*;


@Entity
@Table
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int employeeId;

    @Column
    private String employeeName;

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
}

EmployeeService.java

package com.springdemo.service;

import com.springdemo.model.Employee;

import java.util.List;


public interface EmployeeService {
    public void save(Employee employee);
    public List<Employee> list();
}

EmployeeServiceImpl.java

@service indicate that it’s service layer code. Most probably service layer accessible at Controller Layer. Service layer contains business logic. Service layer communicate with DAO layer and perform necessary database operation.

package com.springdemo.service;

import com.springdemo.dao.EmployeeDAO;
import com.springdemo.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeDAO employeeDAO;

    @Override
    public void save(Employee employee) {
        employeeDAO.save(employee);
    }

    @Override
    public List<Employee> list() {
        return employeeDAO.list();
    }
}

resources/application.properties

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/demo_database_1
jdbc.username = root
jdbc.password =
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = false
hibernate.format_sql = false

createEmployee.jsp

<html>
<body>
  <form action="saveEmployee" method="post">
        Name: <input type="text" name="employeeName">
        <input type="submit" value="Save">
    </form>
</body>
</html>

viewEmployee.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
    <h1>Employee List</h1>
    <table border="1">
        <tr>
            <th> Id
            <th> Name
        </tr>
  <c:forEach var="employee" items="${employees}">
        <tr>
            <td> <c:out value="${employee.employeeId}" />
            <td> <c:out value="${employee.employeeName}" />
        </tr>
    </c:forEach>
    </table>
</body>
</html>

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
         http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.springdemo"/>

    <mvc:annotation-driven/>

    <context:property-placeholder location="classpath:application.properties"/>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <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>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan">
            <list>
                <value>com.springdemo.model</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager"  class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

web.xml

<web-app version="2.4"
  xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>Spring MVC Application</display-name>

    <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

download source code

spring-hibernate-xml-configuration

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

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