In the previous tutorial, we have seen about Spring MVC Login Example, and we have validated the user credentials manually i.e we didn’t communicate with the Hibernate Framework for validating the user credentials.

In this tutorial, we are going to integrate the hibernate framework to spring MVC.

Spring Hibernate Example

dependencies

I have attached Spring dependencies in the previous tutorials

  • hibernate-core-4.1.5.Final.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • javassist-3.12.1.GA.jar
  • mysql-connector-java-5.0.6-bin.jar
  • commons-dbcp-1.2.jar
  • commons-pool-1.5.jar
  • commons-codec-1.4.jar
  • dom4j-1.6.1.jar
  • Creating the Login Page

Login.jsp

Login.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>User Login.</title>
    </head>
    <body>
        <h4>User Login.</h4>
        <form:form method="post" name="loginForm">
            <table>
                <tr><td>User Name: </td><td><input name="userName" type="textbox"></td></tr>
                <tr><td>Password: </td><td><input name="password" type="password"></td></tr>
                <tr><td colspan="2" align="right"><input type="submit" value="Submit"></td></tr>
            </table>
            <div style="color:red">${error}</div>
        </form:form>

    </body>
</html>

Creating sample home page

Home.jsp

 

Home.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1 style="color:green">Hello </h1>
                <h1 style="color:royalblue">${userDetails.userName} ,</h1> <h1 style="color:green">welcome to Spring World !</h1>
    </body>
</html>

configure the spring MVC front end controller.

dispatcher-servlet.xml

dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
    <context:annotation-config />
    <context:component-scan base-package="com"  />
    <mvc:annotation-driven />

    <!--properties file location-->
    <context:property-placeholder location="classpath:com/onlinetutorialspoint/dbconfig/dbconfig.properties"/>
    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->

    <bean id="liveDataSource" class="org.apache.commons.dbcp.BasicDataSource" >
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url">
            <value>${db.url}</value>
        </property>
        <property name="username" >
            <value>${db.username}</value>
        </property>
        <property name="password" >
            <value>${db.password}</value>
        </property>
    </bean>
    <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="liveDataSource"/>
        <property name="mappingResources">
            <list>
                <value>com/onlinetutorialspoint/service/Login.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <ref bean="exampleHibernateProperties" />
        </property>
    </bean>
    <bean id="exampleHibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="properties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />

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

DataBase configuration.

dbconfig.properties

dbconfig.properties
db.url=jdbc:mysql://localhost:3306/onlinetutorialspoint?autoReconnect=true

db.username=chandu
db.password=123456

Create a Database Table like below.

MySQL Terminal
CREATE TABLE `Login` (
`id` INT(10) NOT NULL DEFAULT '0',
`userName` VARCHAR(50) NULL DEFAULT NULL,
`password` VARCHAR(50) NULL DEFAULT NULL,
`isactive` TINYINT(4) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'

Create Pojo class for the above table.

Login.java

Login.java
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Login"
    ,catalog="onlinetutorialspoint"
)
public class Login  implements java.io.Serializable {

     private int id;
     private String userName;
     private String password;
     private Byte isactive;

    public Login() {
    }

    public Login(int id) {
        this.id = id;
    }
    public Login(int id, String userName, String password, Byte isactive) {
       this.id = id;
       this.userName = userName;
       this.password = password;
       this.isactive = isactive;
    }

     @Id

    @Column(name="id", unique=true, nullable=false)
    public int getId() {
        return this.id;
    }

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

    @Column(name="userName", length=50)
    public String getUserName() {
        return this.userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Column(name="password", length=50)
    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Column(name="isactive")
    public Byte getIsactive() {
        return this.isactive;
    }

    public void setIsactive(Byte isactive) {
        this.isactive = isactive;
    }

}

Create hbm.xml file for created pojo with respect to the table.

Login.hbm.xml

 

Login.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.onlinetutorialspoint.service.Login" table="Login" catalog="onlinetutorialspoint">
        <id name="id" type="int">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="userName" type="string">
            <column name="userName" length="50" />
        </property>
        <property name="password" type="string">
            <column name="password" length="50" />
        </property>
        <property name="isactive" type="java.lang.Byte">
            <column name="isactive" />
        </property>
    </class>
</hibernate-mapping>

create Model class for communicating

LoginModel.java

LoginModel.java
public class LoginModel {

    private String userName;
    private String password;

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "LoginModel{" + "userName=" + userName + ", password=" + password + '}';
    }
}

Create DAO class for data accessing.

LoginDAO.java

LoginDAO.java
import com.onlinetutorialspoint.service.Login;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class LoginDAO {

    @Autowired
    SessionFactory mySessionFactory;

    @Transactional(value = "transactionManager")
    public Login getUserDetails(String userName) {
        Login login = null;
        try {

            Session currentSession = mySessionFactory.openSession();
            Query query = currentSession.createQuery("from Login where userName='" + userName+"'");
            List list = query.list();
            System.out.println("list : " + list);
            if (list != null) {
                login = (Login) list.get(0);
            }
            return login;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Create LoginController

LoginController.java

LoginController.java
import com.onlinetutorialspoint.dao.LoginDAO;
import com.onlinetutorialspoint.model.LoginModel;
import com.onlinetutorialspoint.service.Login;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("login.htm")
public class LoginController {

    @Autowired
    LoginDAO loginDAO;

    @RequestMapping(method = RequestMethod.GET)
    public String init(ModelMap modelMap) {
        modelMap.put("info", "Hello User");
        return "Login";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String submit(ModelMap modelMap, @ModelAttribute("loginModel") @Valid LoginModel loginModel) {
        String password = loginModel.getPassword();
        String userName = loginModel.getUserName();
        if (password != null && userName != null) {
            Login userDetails = loginDAO.getUserDetails(loginModel.getUserName());
            if (userDetails != null && userDetails.getUserName().trim().equals(userName)
                    && userDetails.getPassword().trim().equals(password)) {
                modelMap.put("userDetails", userDetails);
                return "Home";
            } else {
                modelMap.put("error", "Invalid UserName / Password");
                return "Login";
            }
        } else {
            modelMap.put("error", "Invalid UserName / Password");
            return "Login";
        }
    }
}

Done!
Happy Learning 🙂