Insertion action using Hibernate with Spring and JSP by R4R Team

In this Spring tutorial we will learn how to inset data into a table using mysql database and hibernate. Here we will integrate spring and hibernate together. We all know that hibernate is ORM means Object Relational Mapping. So it can integrate with any kind of framework in java. As we have done with (Servlet, Struts, Swing, etc.)

The integration of Hibernate with Spring we can easy understand by the Example. So we are providing a Spring Hibernate Integration Example in which we Will insert the data into the table.

Step 1. Take a New Project and attatch all jar file of Hibernate and Spring.

Step 2. Create 3 Package in under src folder. There we can store the action file of the action for the scurity and reusablity.

Step 3. Create a table into the database.

create table Product
(
id int not null primary key auto_increment,
product_name varchar(50),
product_price int(10)
)

Step 4. Create a Hibernate configuration file in the src file and select that database which you have create in the mysql.

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/springwork?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping resource="entites/Product.hbm.xml"/>
    <mapping class="entites.Product" package="entites" resource="entites/Product.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

hibernate.revenge.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="springwork"/>
  <table-filter match-name="product"/>
</hibernate-reverse-engineering>

Step 4. Now do one this is the which package we have already created in the src package that will be used into this part. Here we will create some java file in those package which we have created into the src folder.

1. ProductController.java

package controller;

import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.*;
import entites.*;
import model.*;
import java.util.*;
import org.springframework.ui.ModelMap;
/**
 *
 * @author sarvesh
 */
@Controller(value="/product")
@RequestMapping
public class ProductController {
    
    private ProductModel pm = new ProductModel();
    
    
    @RequestMapping(value="/add", method=RequestMethod.GET)
    public String add(ModelMap mm)
    {
        mm.put("pr", new Product());
        return "add";
    }
    
}

2. In the entities package we will create the all entities. Product.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">
<!-- Generated Mar 23, 2015 11:34:54 PM by Hibernate Tools 3.6.0 -->
<hibernate-mapping>
    <class name="entites.Product" table="product" catalog="springwork">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="pname" type="string">
            <column name="pname" length="50" />
        </property>
        <property name="price" type="java.lang.Integer">
            <column name="price" />
        </property>
    </class>
</hibernate-mapping>

2. Product.java

package entites;
// Generated Mar 23, 2015 11:34:51 PM by Hibernate Tools 3.6.0


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;

/**
 * Product generated by hbm2java
 */
@Entity
@Table(name="product"
    ,catalog="springwork"
)
public class Product  implements java.io.Serializable {


     private Integer id;
     private String pname;
     private Integer price;

    public Product() {
    }

    public Product(String pname, Integer price) {
       this.pname = pname;
       this.price = price;
    }
   
     @Id @GeneratedValue(strategy=IDENTITY)

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

    
    @Column(name="pname", length=50)
    public String getPname() {
        return this.pname;
    }
    
    public void setPname(String pname) {
        this.pname = pname;
    }

    
    @Column(name="price")
    public Integer getPrice() {
        return this.price;
    }
    
    public void setPrice(Integer price) {
        this.price = price;
    }

}

Now we need to do one this also here that is: Select to Model package and create some java class.

1. AbstractModel.java

package model;

/**
 *
 * @author sarvesh
 */
public class AbstractModel {
    
}

2. HibernateUtil.java

package model;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author sarvesh
 */
public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

3. ProductModel.java

package model;
import java.util.*;
import entites.*;
/**
 *
 * @author sarvesh
 */
public class ProductModel extends AbstractModel<Product>
{
     public ProductModel()
     {
         super(Product.class);
     }

    public void create(Product pr) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void update() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

Step 5. Now we need to go through the dispatcher-servlet.java

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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">

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

    <!--
    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="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" />

</beans>

2. Now do one thing also that is ApplicationContext.xml

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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">

    <!--bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}" /-->

    <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->

</beans>

3. Now do one this web.xml file 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Step 6. Now do the simple designing work of the application which we want to see on the front end and on the browser.

1. Under the WEB-INF -> jsp folder -> add.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Add New Product</title>
    </head>
    <body>
        <spring:form method="post" commandName="pr" action="add.html">
            <table border="0" cellpadding="2" cellspacing="2">
                
                <tr>
                    <td>Name</td>
                    <td><spring:input path="name"/></td>
                </tr>
                
                <tr>
                    <td>Price</td>
                    <td><spring:input path="price"/></td>
                </tr>
                <tr>
                    <td>Quantity</td>
                    <td><spring:input path="quantity"/></td>
                </tr>
                
                <tr>
                    <td>Description</td>
                    <td><spring:input path="description" cols="20" row="5"/></td>
                </tr>
                
                <tr>
                    <td>&nbsp;</td>
                    <td><input type="submit" value="save"/></td>
                </tr>
            </table>
            
        </spring:form>
    </body>
</html>

Step 7. Now do one this select to the project node and click on right and select to run the application and run.
Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!