Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Saturday, 9 March 2013

Spring Hibernate Integration Hello World Tutorial (Spring + Hibernate + MySql)

Today i will walk you through the integration of Hibernate with a Spring MVC application using annotations. In this particular blog we will create a simple Hello World application in Spring and Hibernate. Our objective for today's discussion id to create a simple registration form using spring's tags, the data is to be persist in a MySql database and after that we will retrieve the data from database and will show the data in table form.

Spring MVC and Hibernate Integration CRUD with Maven

Database
The very first step to start an application is creating a database, lets create a database with name 'beingjavaguys_db' and create a 'USER' table in it. To create database simply copy the script below and run it in your 'query editor'. This will create a database and table with required fields.
DROP TABLE IF EXISTS `USER`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `USER` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `gender` varchar(45) DEFAULT NULL,
  `city` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
) 

Project Structure
Before we start adding some code to our application lets take a look at overall project structure. Create a simple 'web application' project in 'Eclipse' and add all code files to it as mentioned in rest part of this blog.


/WebContent/WEB-INF/web.xml
First of all add some entries to your 'web.xml' so that the 'tomcat container' could understand the behavior of application. Add a servlet entry point for 'DispatcherServlet' to make the container understand that all spring configuration is done in it and going to be used accordingly. Now add 'url-mapping' to 'DispatcherServlet' , this tells the container that all requests with /'.html' extention are going to be handled by spring itself. At the end of the file a entry for welcome file is added that indicates the starting point of the application.

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

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

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>


/WebContent/index.jsp
In 'index.jsp' a 'SendRedirect' is added that redirects the control to '/register.html' so that spring could take the command from this point.
<%@page import="com.sun.mail.iap.Response"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%response.sendRedirect("register.html"); %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

/src/com/beingjavaguys/controller/HomeController.java
We have added a controller with name 'Home Controller' and configured it using required mappings. '@Controller' tells that the class is going to be used as a controller for the application. '@RequestMapping' tells that the method will behave like an action for the mentioned 'url pattern'. Whenever a request pattern will match to the pattern specified in '@RequestMapping' the code written in related method will be executed. Here you can see that the every action is returning an object of 'ModelAndView' class. 'ModelAndView' class offers a number of things to the application, the very first parameter that is passed to it, represents the name of view(required jsp file) that is going to be rendered after completion of action's code. The second parameter indicated a String value key for the object that is placed as third parameter. Using these capabilities we can send an object to view associated with a key.

package com.beingjavaguys.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.beingjavaguys.domain.User;
import com.beingjavaguys.service.UserService;

@Controller
public class HomeController {

   @Autowired
    private UserService userService;


   @RequestMapping("/register")
    public ModelAndView getRegisterForm(@ModelAttribute("user") User user,
            BindingResult result) {

        ArrayList<String> gender = new ArrayList<String>();
        gender.add("Male");
        gender.add("Female");

        ArrayList<String> city = new ArrayList<String>();
        city.add("Delhi");
        city.add("Kolkata");
        cit.add("Chennai");
        city.add("Bangalore");

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("gender", gender);
        model.put("city", city);

        System.out.println("Register Form");
        return new ModelAndView("Register", "model", model);

    }


    @RequestMapping("/saveUser")
    public ModelAndView saveUserData(@ModelAttribute("user") User user,
            BindingResult result) {

        userService.addUser(user);
        System.out.println("Save User Data");
        return new ModelAndView("redirect:/userList.html");

    }


    @RequestMapping("/userList")
    public ModelAndView getUserList() {

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("user", userService.getUser());
        return new ModelAndView("UserDetails", model);

    }

}


/src/com/beingjavaguys/dao/UserDao.java
DAO stand for data access object, it makes it easy to communicate the application with database. We are using an interface here this implements standard industrial practices. Required methods are declared here and being implemented in related implementation class associated with it.
package com.beingjavaguys.dao;

import java.util.List;
import com.beingjavaguys.domain.User;


public interface UserDao {
public void saveUser ( User user );
public List<User> getUser();

}


/src/com/beingjavaguys/dao/UserDaoImpl.java
This is implementation class for UserDao interface, all methods declared in UserDao interface are implemented here to achieve the goal. 'saveUser()' method takes an User's object as parameter and persists it in the database using 'sessionFactory' object. Similarly 'getUser()' method is returning a list of User's object using a Hibernate Criteria query.
package com.beingjavaguys.dao;

import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.beingjavaguys.domain.User;


@Repository("userDao")
public class UserDaoImpl implements UserDao {


    @Autowired
    private SessionFactory sessionfactory;


    @Override
    @Transactional
    public void saveUser(User user) {
        sessionfactory.getCurrentSession().saveOrUpdate(user);
    }


    @Override
    @Transactional
    public List<User> getUser() {

        @SuppressWarnings("unchecked")
        List<User> userlist = sessionfactory.getCurrentSession()
                .createCriteria(User.class).list();
        return userlist;

    }

}

/src/com/beingjavaguys/domain/User.java
To represent User entity within the application and to persist User's objects we uses a User class with all required fields. This is nothing but a simple java bean with some Hibernate annotations. @Entity tells that the class is a domain class that maps to a table in the database. The name attribute of '@Table' specifies the table name in the database. @Id tells that the related column is going to represent the 'primary key' for the table and @GeneratedValue show auto increment nature for related column. The name attribute of '@Column' specifies the related column name for the field.

package com.beingjavaguys.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name = "USER")
public class User {



    @Id
    @GeneratedValue
    @Column(name = "user_id")
    private int id;



    @Column(name = "first_name")
    private String firstName;


    @Column(name = "last_name")
    private String lastName;


    @Column(name = "gender")
    private String gender;



    @Column(name = "city")
    private String City;


    public int getId() {
        return id;
    }


    public void setId(int id) {
        this.id = id;

    }


    public String getFirstName() {
        return firstName;

    }


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

    }


    public String getLastName() {
        return lastName;

    }


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


    public String getGender() {
        return gender;

    }


    public void setGender(String gender) {
        this.gender = gender;

    }


    public String getCity() {
        return City;
    }


    public void setCity(String city) {
        City = city;
    }
}


/src/com/beingjavaguys/service/UserService.java
Service layer is added here to implement two layer architecture for the application, it works some kind of interface in between the application and database transactions. Its always a good practice to have a service layer in your application so that the application data can be isolated to database code and reusability can be enhanced.
package com.beingjavaguys.service;

import java.util.List;
import com.beingjavaguys.domain.User;
public interface UserService {
    public void addUser(User user);
    public List<User> getUser();

}


/src/com/beingjavaguys/service/UserServiceImpl.java
This is implementation for UserService interface, service methods are called in application controlled to perform database stuff.

package com.beingjavaguys.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.beingjavaguys.dao.UserDao;
import com.beingjavaguys.domain.User;


@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class UserServiceImpl implements UserService {


    @Autowired
    UserDao userDao;
    @Override
    public void addUser(User user) {
        userDao.saveUser(user);

    }


    @Override
    public List<User> getUser() {
        return userDao.getUser();

    }
}

/src/jdbc.properties
A property class is added here to specify all required database properties in a separated file, show_sql=true make all database queries to show on console.

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/beingjavaguys_db
database.user=root
database.password=root
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create/update 


/WebContent/WEB-INF/dispatcher-servlet.xml
Dispatcher servlet is the root of an spring application, all spring configurations goes here is a single file. The 'jspViewResolver' bean specifies the view files path and its prefix and suffix attributes makes it easy to use simple view names in application rather that specifying full path.

<?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: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/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-3.0.xsd">

    <context:property-placeholder location="classpath:jdbc.properties" />
    <context:component-scan base-package="com.beingjavaguys" />
    <tx:annotation-driven transaction-manager="hibernateTransactionManager" />
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.beingjavaguys.domain.User</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            </props>
        </property>
    </bean>



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

</beans>


/WebContent/WEB-INF/view/Register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Being Java Guys | Registration Form</title>
</head>
<body>
<center>

<div style="color: teal;font-size: 30px">Being Java Guys | Registration Form</div>
<br><br>
<c:url var="userRegistration" value="saveUser.html"/>
<form:form id="registerForm" modelAttribute="user" method="post" action="${userRegistration}">
<table width="400px" height="150px">
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td><form:input  path="firstName"/></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td><form:input  path="lastName"/></td>
</tr>
<tr>
<td><form:label path="gender">Gender</form:label></td>
<td><form:radiobuttons path="gender" items="${model.gender}"/></td>
</tr>
<tr>
<td><form:label path="city">City</form:label></td>
<td><form:select path="city" items="${model.city}"></form:select></td>
</tr>
<tr><td></td><td>
<input type="submit" value="Register" />
</td></tr>
</table>
</form:form>
<br>
<a href="userList.html" >Click Here to see User List</a>
</center>
</body>
</html>


/WebContent/WEB-INF/view/UserDetails.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Being Java Guys | User Details</title>
</head>
<body>
<center>

<div style="color: teal;font-size: 30px">Being Java Guys | User Details</div>
<br><br>
<c:if test="${!empty user}">
<table border="1" bgcolor="black" width="600px">
<tr style="background-color: teal;color: white;text-align: center;" height="40px">
<td>User Id</td>
<td>First Name</td>
<td>Last Name</td>
<td>Gender</td>
<td>City</td>
</tr>
<c:forEach items="${user}" var="user">
<tr style="background-color:white;color: black;text-align: center;" height="30px" >
<td><c:out value="${user.id}"/></td>
<td><c:out value="${user.firstName}"/></td>
<td><c:out value="${user.lastName}"/></td>
<td><c:out value="${user.gender}"/></td>
<td><c:out value="${user.city}"/></td>
</tr>
</c:forEach>
</table>
</c:if>
<br>
<a href="register.html" >Click Here to add new User</a>
</center>
</body>
</html>


Here we are done with creating a simple hello world application using Spring and Hibernate. Just run your application on server, if everything went right you will see output something like these screens showing below.




In this blog we went through Spring, Hibernate Integration process and we get to know 'How to create a simple hello world applicaton is springa and hibernate using annotations'. In upcoming blogs we will dive into some others tutorials using spring and hibernate technologies. 









Thanks for reading !
Being Java Guys Team

Download "Spring Hibernate Integration Example project" from "SkyDrive"





59 comments:

  1. Here i didn't found register.jsp and UserDetails.jsp page. If anybody mention in here then helpful for me.

    ReplyDelete
  2. Hey please upload register.jsp and UserDetails.jsp pages...or give a link to download a source code.

    ReplyDelete
  3. will try it out. looking cool. thank you.

    ReplyDelete
  4. @Transactional annotation has to be added in the Dao class to make sure the operation are within a transaction.

    ReplyDelete
  5. Please add all Annotations,
    and
    Advance the topic to login form.

    Thanks

    ReplyDelete
    Replies
    1. Hi, i ama done with adding missed annotation.

      To get login form part of it, visit http://www.beingjavaguys.com/2013/03/how-to-use-spring-security.html

      Thanks

      Delete
  6. Gr8 article. Successfully executed. Thank u so much. It will help me to do next project task.

    ReplyDelete
    Replies
    1. Thanks, i am glad to hear that my work w'll help u :)

      Delete
  7. Hi, am facing this issue :
    Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist

    ReplyDelete
  8. wow dude,awesome article

    ReplyDelete
  9. org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: The database returned no natively generated identity value
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:659)
    org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:563)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)


    =======================================
    It is showing this Exception

    ReplyDelete
  10. if anybody has this complete example then please mail me
    ramkumar652@gmail.com

    ReplyDelete
  11. if anybody has this complete example then please mail me
    ramkumar652@gmail.com

    ReplyDelete
    Replies
    1. 'Download Link' is just there at the end of blog.
      Get the complete project from there !

      Delete
    2. register is mentioned in @request mapping and .html is mentioned in web .xml url maaping so on hitting register.html homecontroller method is called.

      Delete
  12. Hello Ram Kumar.....

    open your eyes and look at the end the full code is just there.......

    and being java guys nyc example

    ReplyDelete
  13. Gud article, but if you ask me it only explains the most "common" annotations, i.e. Autowired, RequestMapping, Id, etc, you don't say a word about ModelAttribute or Transactional, and the example doesn't contains any foreign key; still, gud article

    ReplyDelete
  14. It is showing this Exception:
    org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.MySQLDialect

    Hibernate4 then tried to use the same story...

    ReplyDelete
  15. nice tutorial for freshers and experienced

    ReplyDelete
  16. Excellent Job !!! Thank you !

    ReplyDelete
  17. Very good example.

    Thanks
    Vishal Bhatt

    ReplyDelete
  18. Thanks for your posting.It was very easy to understand.
    Can you post some material that throws some light on drawback of hibernate as compared to JPA. Also how can we achieve loose coupling without using spring.
    Thanks in advance

    ReplyDelete
  19. It's nice tutorial compare to all sites
    Thanks lot

    ReplyDelete
  20. Hi Your article was good.After lot of searching i found some good one here
    I am using oracle 11g database.Accordingly i have made changes in the database properties
    i have used ojdbc14.jar file
    but i get this exception

    HTTP Status 500 - Request processing failed; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection

    Kindly help m in this regard

    ReplyDelete
  21. what about regester.jsp and userdetails.jsp? these files are missing

    ReplyDelete
    Replies
    1. Those are simple jsp files, you can get them by downloading complete project.
      'Download Link' is just there at the end of blog.

      Delete
    2. Hi, instead of MySql, am using Oracle 11g, while am saving some user, it is neither updating the database, not it is throwing some error...any idea?

      Delete
  22. Good tutorial.. I'm searching for Spring MVC + Hibernate with Annotations from two days. Today with this tutorial I found a nice solution. Thanks

    ReplyDelete
  23. Good Article, really helped me in beginning with spring and hibernate. Thanks a lot.

    ReplyDelete
  24. Thank you for the article. Do you have an updated version that forgoes the web.xml part?? I am using Spring's annotations so that I don't have a web.xml file.

    ReplyDelete
  25. Thank you , it's very useful.

    ReplyDelete
  26. thank u..gud information..

    ReplyDelete
  27. thank you so much for providing those examples that works when downloaded... Keep the good work...

    ReplyDelete
  28. I have error in "The method saveOrUpdate(User) is undefined for the type Object" what should i do?

    ReplyDelete
  29. Mamuka wrote:

    I added
    update
    to sessionFactory bean config and it created table in database
    no need to run sql statement

    ReplyDelete
  30. still Mamuka:
    I added property : hibernate.hbm2ddl.auto and sat it to true

    ReplyDelete
  31. Excellent and thank you so much

    ReplyDelete
  32. Cool, thanks!!!

    ReplyDelete
  33. Hi Nagesh...that is very cool tutorial. But I found error when start Tomcat in eclipse :

    Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.beingjavaguys.dao.UserDao com.beingjavaguys.service.UserServiceImpl.userDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.beingjavaguys.dao.UserDaoImpl.sessionfactory; nested exception is java.lang.NoClassDefFoundError: [Lorg/hibernate/engine/FilterDefinition


    I Always found the same error if I create other project.
    spring version : 4.0.2
    hibernate version : 4.3.4
    Eclipse kepler

    Please help..thanks

    ReplyDelete
  34. I tried this as starting point. But my problem with @Transactional in service, is that when I am in controller or view, I get Lazy initialization error when I have one to many relationships. I tried OpenSessionInViewFilter but it does not fix it.

    ReplyDelete
  35. can you please tell me how to delete record in the same example.

    ReplyDelete
  36. Hi ,

    I am getting below error please help me out

    java.sql.SQLException: ORA-02289: sequence does not exist

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:799)
    at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1038)

    ReplyDelete
  37. worked perfect example..

    if possible can i please get this example without using annotation

    ReplyDelete
  38. Very good article. Good for beginners. It would have been even better if the jar files that were required were listed at the beginning. Nonetheless, it is a good example. Thanks for posting.

    ReplyDelete
  39. Very very very thanks 2 u..

    ReplyDelete
  40. Gr8 article. Successfully executed. Thank u so much. It will help me to do next project task.
    Great Work..... Really Awesome..
    Actually i was struggling in submit page .but now it happend.
    Thank you so much .i executed my project successfully.
    Can you help me in search page which search results display on the same page.
    Thanks

    ReplyDelete
  41. very very very thanks !!!

    ReplyDelete
  42. Good article, but what if you don't wish to hard-code the options for the drop down, but want to have them pulled from a DB, how do you go about that?

    ReplyDelete
  43. Can u add Login Part aswell ..Thanks in Advance

    ReplyDelete
  44. Thank you so much....................

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft