Tuesday, July 06, 2010

Simple SpringToHibernate Example




Simple SpringToHybernate Example : This is Spring Program using Hibernate to perform the Data base operation with MySQL. Hibernate provides many different way to perform persistence operation on Database i.e. Insert,Update Delete etc. This program have the same flow as we had seen in the simple Spring MVC Example.




Web.xml:

xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<servlet>

<servlet-name>enterDataservlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>

<load-on-startup>1load-on-startup>

servlet>

<servlet-mapping>

<servlet-name>enterDataservlet-name>

<url-pattern>*.htmurl-pattern>

servlet-mapping>

<welcome-file-list>

<welcome-file>redirect.jspwelcome-file>

welcome-file-list>

web-app>

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

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">

<value>/WEB-INF/jsp/value>

property>

<property name="suffix">

<value>.jspvalue>

property>

bean>

<bean id="enterDataController" class="Controller.ShowPage">

bean>

<bean id="loginFormController" class="Controller.LoginFormController">

<property name="formView" value="LogIn" />

<property name="successView" value="ResultPage.htm" />

<property name="commandName" value="loginData" />

<property name="commandClass" value="Controller.LoginFormData" />

bean>

<bean id="resultPageController" class="Controller.ResultPageController">

bean>

<bean id="urlMapping"

class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="urlMap">

<map>

<entry key="EnterData.htm">

<ref bean="enterDataController" />

entry>

<entry key="LogIn.htm">

<ref bean="loginFormController" />

entry>

<entry key="ResultPage.htm">

<ref bean="resultPageController" />

entry>

map>

property>

bean>

beans>

EnterData.jsp:

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Database Modificationtitle>

head>

<body>

No Action has been done on the Database side please check the DB for more confirmation.

body>

html>

LogIn.jsp:

<html>

<body>

<form:form commandName="loginData" method="POST">

ID:<form:input path="id"/><br/>

Name:<form:input path="name"/><br/>

<input type="submit" value="Insert1" name="Insert"/>

<input type="submit" value="Update1" name="Update"/>

<input type="submit" value="Delete1" name="Delete"/>

<input type="submit" value="No_Submit" name="No_Submit"/>

form:form>

body>

html>

ResultPage.jsp:

<html>

<body>

<h1>Data Base is updated Successfully!h1>

body>

html>

LoginFormController:

package Controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

import org.springframework.validation.BindException;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.SimpleFormController;

import org.springframework.web.servlet.view.RedirectView;

public class LoginFormController extends SimpleFormController {

@Override

public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

request.getSession().setAttribute("FORM_DATA", formData);

ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

if (request.getParameter("Insert") != null) {

// delete object

return Insert(request, response, command, errors);

} else if (request.getParameter("Update") != null) {

// Update object

return Update(request, response, command, errors);

} else if (request.getParameter("Delete") != null) {

// Delete object

return Delete(request, response, command, errors);

}

else {

// save object

return new ModelAndView("EnterData");

}

}

public ModelAndView Insert(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

request.getSession().setAttribute("FORM_DATA", formData);

/*

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("insert into test_table (id, name) values (?, ?)", new Object[] {formData.getId(), formData.getName()});

*/

Session session = null;

try{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

session =sessionFactory.openSession();

//Create new instance of Contact and set values in it by reading them from form object

test_table objtest_table = new test_table();

objtest_table.setId(formData.getId());

objtest_table.setName(formData.getName());

session.save(objtest_table);

}catch(Exception e){

e.printStackTrace();

}finally{

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

return modelAndView;

}

public ModelAndView Update(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

request.getSession().setAttribute("FORM_DATA", formData);

/*

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("update test_table set name = ? where id = ?", new Object[] {formData.getName(),formData.getId()});

*/

Session session = null;

try {

SessionFactory fact = new Configuration().configure().buildSessionFactory();

session = fact.openSession();

Transaction tr = session.beginTransaction();

test_table objtest_table = (test_table)session.get

(test_table.class, formData.getId());

objtest_table.setName(formData.getName());

session.update(objtest_table);

tr.commit();

session.close();

}

catch(Exception e){

System.out.println(e.getMessage());

} finally{

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

return modelAndView;

}

public ModelAndView Delete(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

request.getSession().setAttribute("FORM_DATA", formData);

/*

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("delete from test_table where id = ?", new Object[] {formData.getId()});

*/

Session sess = null;

try {

SessionFactory fact = new Configuration().configure().buildSessionFactory();

sess = fact.openSession();

test_table objtest_table = (test_table)sess.get(test_table.class, formData.getId());

Transaction tr = sess.beginTransaction();

objtest_table.setName(formData.getName());

sess.delete(objtest_table);

tr.commit();

sess.close();

}

catch(Exception e){

System.out.println(e.getMessage());

} finally{

// Actual contact insertion will happen at this step

sess.flush();

sess.close();

}

ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

return modelAndView;

}

}

LoginFormData:

package Controller;

public class LoginFormData {

private String id;

private String name;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

ResultPageController:

package Controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.AbstractController;

public class ResultPageController extends AbstractController {

@Override

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

return new ModelAndView("ResultPage");

}

}

ShowPage:

package Controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.AbstractController;

public class ShowPage extends AbstractController {

@Override

protected ModelAndView handleRequestInternal(HttpServletRequest request,

HttpServletResponse response) throws Exception {

return new ModelAndView("EnterData");

}

}

SiddhuTestExample:

package Controller;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

/**

* @author Siddharatha Dhumale

*

* Hibernate example to inset data into Contact table

*/

public class SiddhuTestExample {

public static void main(String[] args) {

Session session = null;

try{

// This step will read hibernate.cfg.xml and prepare hibernate for use

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

session =sessionFactory.openSession();

//Create new instance of Contact and set values in it by reading them from form object

System.out.println("Inserting Record");

test_table objSiddhu_Test_table = new test_table();

objSiddhu_Test_table.setId("1");

objSiddhu_Test_table.setName("Deepak");

session.save(objSiddhu_Test_table);

System.out.println("Done");

}catch(Exception e){

System.out.println(e.getMessage());

}finally{

// Actual contact insertion will happen at this step

session.flush();

session.close();

}

}

}

test_table:

package Controller;

/**

* @author Siddharatha Dhumale

*

*

* Java Class to map to the datbase Contact Table

*/

public class test_table {

private String id;

private String name;

/**

* @return

*/

public String getId() {

return id;

}

/**

* @return

*/

public void setId(String id) {

this.id = id;

}

/**

* @return

*/

public String getName() {

return name;

}

/**

* @return

*/

public void setName(String name) {

this.name = name;

}

}

Hibernate.cfg.cml:

xml version='1.0' encoding='utf-8'?>

DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driverproperty>

<property name="hibernate.connection.url">jdbc:mysql://localhost/siddhutest_dbproperty>

<property name="hibernate.connection.username">rootproperty>

<property name="hibernate.connection.password">property>

<property name="hibernate.connection.pool_size">10property>

<property name="show_sql">trueproperty>

<property name="dialect">org.hibernate.dialect.MySQLDialectproperty>

<property name="hibernate.hbm2ddl.auto">updateproperty>

<mapping resource="test_table.hbm.xml"/>

session-factory>

hibernate-configuration>

Test_table.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">

<hibernate-mapping>

<class name="Controller.test_table" table="test_table">

<id name="id" column="id" >

<generator class="assigned"/>

id>

<property name="name">

<column name="name"/>

property>

class>

hibernate-mapping>

No comments: