JaiswalTraining

Get the online training

Corejava Servlet Jsp  Php  Hibernate  Ajax Web Service   Ejb2.1 Ejb3.0 Struts Struts2  JPA Spring Ibatis   JSF    JSF2.0  CoreJavaDesignPattern    Jquery  Flex J2EE-Design-Patterns  Jboss7  Maven  Contact Me                                                                                                                                                                        
            IGNOU SMU PTU Project                                           Training                                                                                                                              
              

Contact Us  0091- 9210721663         jaiswaltraining@gmail.com




Corejava
Servlet
Jsp
Php
Hibernate
Ajax
Web Service
Ejb2.1
Ejb3.0
Struts  
Struts2
JPA
Spring
Ibatis
JSF
JSF2.0
CoreJavaDesignPattern
Jquery
Flex
J2EE-Design-Patterns
Jboss7
Maven







Spring DAO Module


Introduction
he DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes.

  • Define connection parameters
  • Open the connection
  • Specify the statement
  • Prepare and execute the statement
  •  Set up the loop to iterate through the results (if any)
  •  Do the work for each iteration
  • Process any exception
  • Handle transactions
  • Close the connection
The Spring Framework takes care of all the grungy, low-level details that can make JDBC such a tedious API to develop with.

Benefits:
  • Make JDBC essier to use and less error prone
  • Framework handle the creation and release of  resources.
  • ]Framework takes care of all exception handling
JdbcDaoSupport, which is the super class for accessing data using JDBC. You must provide a
DataSource instance to it. This class, in turn, provides the JdbcTemplate instance, created from
the supplied DataSource instance, to the sub-class.

JDBCTemplate

The JdbcTemplate class is the central class in the JDBC core package. It simplifies the use of JDBC since it handles the creation and release of resources. This helps to avoid common errors such as forgetting to always close the connection.
  • Execute sql queries,update statements or stored procedures calls.
  • Iteration over ResultSet and Extraction of  returned parametere values.
when using the JdbcTemplate class, a fix task  is to configure a DataSource in your Spring configuration file,

<bean id="datasource" 
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

<bean id="jdbctemplate" 
class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="datasource"/>

</bean>

The following are the steps required to make use of JdbcTemplate:

1. Develop the bean
2. Configure the bean and JdbcTemplate
3. Develop the client

Develop the bean

The bean or POJO is similar to any other POJO used with the Spring Framework
except for one difference. The POJO developed to be used with JdbcTemplate requires a setter for the
DataSource object

NamedParameterJdbcTemplate:- provides a wrapper for Named Parameter queries of JDBC. It
wraps the JdbcTemplate to provide a more convenient way of handling parameterized queries
instead of the conventional "?" placeholder provided by JDBC, thus making it easier to use
multiple parameters.

SimpleJdbcTemplate

The SimpleJdbcTemplate class is a wrapper around the classic JdbcTemplate that takes advantage of Java 5 language features such as varargs and autoboxing.



<bean id="datasource" 
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

<bean id="simplejdbctemplate" 
class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
        <property name="dataSource" ref="datasource"/>

</bean>


Example:-
In this example we are fetching students' records from database.

package mypack;

public class Student {
  private int roll;
  private String name;

  public void setName(String name) {
    this.name = name;
  }

  public void setRoll(int roll) {
    this.roll = roll;
  }

  public String getName() {
    return name;
  }

  public int getRoll() {
    return roll;
  }

}

package mybean;

import java.awt.List;
import java.sql.ResultSet;
import java.sql.SQLException;

import mypack.Student;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class JavaBean {

  private JdbcTemplate jdbctemplate;

  public void setJdbctemplate(JdbcTemplate jdbctemplate) {
    this.jdbctemplate = jdbctemplate;
  }

  public List searchStudent(Student stud) {
    List list = new List();
    list = (Listjdbctemplate.queryForObject("select * from stud",
        new RowMapper() {
          public Object mapRow(ResultSet rs, int rowNum)
              throws SQLException {
            Student stud = new Student();
            stud.setRoll(rs.getInt(1));
            stud.setName(rs.getString(2));
            return stud;
          }
        });
    return list;
  }
}

SpringConfiguration.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/
schema/beans"

  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan
ce" 
xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework
.org/schema/beans http://www.springframewo
rk.org/schema/beans/spring-beans-2.5.xsd"
>

  <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
    <property name="url" value="jdbc:oracle:thin:@localhost:1521:XE" />
    <property name="username" value="system" />
    <property name="password" value="manager" />
  </bean>

  <bean id="jdbctemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource" />
  </bean>
  <bean id="javabean" class="mybean.JavaBean">
    <property name="jdbctemplate" ref="jdbctemplate" />
  </bean>
</beans>





web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.o
rg/2001/XMLSchema-instance" 
xmlns="http
://java.sun.com/xml/ns/javaee" 
xmlns:web="ht
tp://java.sun.com/xml/ns/javaee/web-app_2_5.xs
xsi:schemaLocation="http://java.sun.com/xml/ns/
javaee http://java.sun.com/xml/ns/javaee/web-a
p_2_5.xsd" 
id="WebApp_ID" version="2.5">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/SpringConfiguration.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context
.ContextLoaderListener</listener-
class>
  </listener>
  <welcome-file-list>
    <welcome-file>welcome.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>ShowRecords</display-name>
    <servlet-name>ShowRecords</servlet-name>
    <servlet-class>myservlet.ShowRecords</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ShowRecords</servlet-name>
    <url-pattern>/ShowRecords</url-pattern>
  </servlet-mapping>
</web-app>



ShowRecords.java(Servlet file)

package myservlet;

import java.awt.List;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support
.WebApplicationContextUtils;


import mybean.JavaBean;
import mypack.Student;

public class ShowRecords extends HttpServlet {

  protected void doGet(HttpServletRequest request,
      HttpServletResponse response)
throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    Student stud = new Student();
    ServletContext stcx = getServletContext();
    WebApplicationContext springcontainer =
WebApplicationContextUtils

        .getRequiredWebApplicationContext(stcx);
    JavaBean javabean = (JavaBeanspringcontainer.
getBean
("javabean");

    ArrayList arrlist = new ArrayList();
    List list = javabean.searchStudent(stud);
    arrlist.add(list);

    Iterator iterator = arrlist.iterator();
    while (iterator.hasNext()) {
      stud = (Studentiterator.next();
      out.print(stud.getRoll() "------ " +
 stud.getName
() "</br>");
      out.print("</br>");

    }

  }

}


<h2><font color="green"></>Welcome to Student Database</font></h2></br>
</br>
<a href="./ShowRecords">Show the Records</a>


Output