Saturday, May 12, 2012

Hibernate With Spring DAO

In this tutorial you will see how to integrate spring DAO and hibernate. I assume you are comfortable with both spring and hibernate. At the end of this example you will learn  how to use Spring DAO . Here I am using MyEcplise IDE and Oracle 10g Database.
****************************************************************
CREATE TABLE  "CONTACTS" 
   ( "ID" NUMBER(22,0) NOT NULL ENABLE, 
 "FIRSTNAME" VARCHAR2(4000 CHAR), 
 "LASTNAME" VARCHAR2(4000 CHAR), 
 "CELL_NO" VARCHAR2(4000 CHAR), 
 "EMAIL_ID" VARCHAR2(4000 CHAR), 
 "WEBSITE" VARCHAR2(4000 CHAR), 
 "BIRTHDATE" TIMESTAMP (6), 
 "CREATED" VARCHAR2(255 CHAR), 
  PRIMARY KEY ("ID") ENABLE
   )
/
*****************************************************************
<?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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
 <property name="dialect">
  org.hibernate.dialect.Oracle10gDialect
 </property>
 <property name="connection.url">
  jdbc:oracle:thin:@localhost:1521:xe
 </property>
 <property name="connection.username">venkat</property>
 <property name="connection.password">venkat</property>
 <property name="connection.driver_class">
  oracle.jdbc.driver.OracleDriver
 </property>
 <property name="myeclipse.connection.profile">Spring_JDBC</property>
 <mapping resource="com/venkat/hibernate/Contacts.hbm.xml" />
</session-factory>

</hibernate-configuration>
*********************************************************************************
<?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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


 <bean id="sessionFactory"
  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="configLocation"
   value="file:src/hibernate.cfg.xml">
  </property>
 </bean>
 <bean id="ContactsDAO" class="com.venkat.hibernate.ContactsDAO">
  <property name="sessionFactory">
   <ref bean="sessionFactory" />
  </property>
 </bean></beans>
*******************************************************************************
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.venkat.hibernate.Contacts" table="CONTACTS" schema="VENKAT">
        <id name="id" type="java.math.BigDecimal">
            <column name="ID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="firstname" type="java.lang.String">
            <column name="FIRSTNAME" length="4000" />
        </property>
        <property name="lastname" type="java.lang.String">
            <column name="LASTNAME" length="4000" />
        </property>
        <property name="cellNo" type="java.lang.String">
            <column name="CELL_NO" length="4000" />
        </property>
        <property name="emailId" type="java.lang.String">
            <column name="EMAIL_ID" length="4000" />
        </property>
        <property name="website" type="java.lang.String">
            <column name="WEBSITE" length="4000" />
        </property>
        <property name="birthdate" type="java.util.Date">
            <column name="BIRTHDATE" length="7" />
        </property>
        <property name="created" type="java.lang.String">
            <column name="CREATED" />
        </property>
    </class>
</hibernate-mapping>
*************************************************************************
package com.venkat.hibernate; import java.math.BigDecimal; import java.util.Iterator; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSpringDAO { /** * @param args */ public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml"); ContactsDAO dao= context.getBean("ContactsDAO",ContactsDAO.class); Contacts contact=new Contacts(new BigDecimal(234)); dao.save(contact); List<Contacts> list=dao.findAll(); System.out.println("contacts Size "+list.size()); for (Iterator iterator = list.iterator(); iterator.hasNext();) { Contacts contacts = (Contacts) iterator.next(); System.out.println("contact ID is "+contacts.getId()); } } }
******************************************************************************
package com.venkat.hibernate; import java.util.List; import org.hibernate.LockMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; /** * A data access object (DAO) providing persistence and search support for * Contacts entities. Transaction control of the save(), update() and delete() * operations can directly support Spring container-managed transactions or they * can be augmented to handle user-managed Spring transactions. Each of these * methods provides additional information for how to configure it for the * desired type of transaction control. * * @see com.venkat.hibernate.Contacts * @author Venkat */ public class ContactsDAO extends HibernateDaoSupport { private static final Logger log = LoggerFactory .getLogger(ContactsDAO.class); protected void initDao() { // do nothing } public void save(Contacts transientInstance) { log.debug("saving Contacts instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Contacts persistentInstance) { log.debug("deleting Contacts instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Contacts findById(java.math.BigDecimal id) { log.debug("getting Contacts instance with id: " + id); try { Contacts instance = (Contacts) getHibernateTemplate().get( "com.venkat.hibernate.Contacts", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Contacts instance) { log.debug("finding Contacts instance by example"); try { List results = getHibernateTemplate().findByExample(instance); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Contacts instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Contacts as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List<Contacts> findAll() { log.debug("finding all Contacts instances"); try { String queryString = "from Contacts"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Contacts merge(Contacts detachedInstance) { log.debug("merging Contacts instance"); try { Contacts result = (Contacts) getHibernateTemplate().merge( detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Contacts instance) { log.debug("attaching dirty Contacts instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Contacts instance) { log.debug("attaching clean Contacts instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public static ContactsDAO getFromApplicationContext(ApplicationContext ctx) { return (ContactsDAO) ctx.getBean("ContactsDAO"); } }
********************************************************************************
package com.venkat.hibernate; import java.math.BigDecimal; import java.util.Date; /** * Contacts entity. @author MyEclipse Persistence Tools */ public class Contacts implements java.io.Serializable { // Fields private BigDecimal id; private String firstname; private String lastname; private String cellNo; private String emailId; private String website; private Date birthdate; private String created; // Constructors /** default constructor */ public Contacts() { } /** minimal constructor */ public Contacts(BigDecimal id) { this.id = id; } /** full constructor */ public Contacts(BigDecimal id, String firstname, String lastname, String cellNo, String emailId, String website, Date birthdate, String created) { this.id = id; this.firstname = firstname; this.lastname = lastname; this.cellNo = cellNo; this.emailId = emailId; this.website = website; this.birthdate = birthdate; this.created = created; } // Property accessors public BigDecimal getId() { return this.id; } public void setId(BigDecimal id) { this.id = id; } public String getFirstname() { return this.firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return this.lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getCellNo() { return this.cellNo; } public void setCellNo(String cellNo) { this.cellNo = cellNo; } public String getEmailId() { return this.emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getWebsite() { return this.website; } public void setWebsite(String website) { this.website = website; } public Date getBirthdate() { return this.birthdate; } public void setBirthdate(Date birthdate) { this.birthdate = birthdate; } public String getCreated() { return this.created; } public void setCreated(String created) { this.created = created; } }

Spring DAO

We'll wrap up discussion on the Spring JDBC support by using the DAO support classes that Spring provides out of the box. We'll see how this makes our DAO classes cleaner than ever.

org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport
Extension of JdbcDaoSupport that exposes a SimpleJdbcTemplate as well. Only usable on Java 5 and above. 


*************************************************************
package com.venkat;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.venkat.dao.CricketDAO;


public class TestCricket {


public static void main(String[] args) {


ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
CricketDAO dao= context.getBean("cricketDao",CricketDAO.class);
System.out.println(dao.getCricketCount());
}


}
*****************************************************************
package com.venkat.dao;

import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

public class CricketDAO extends SimpleJdbcDaoSupport{
public int getCricketCount()
{
String sql="select count(*) from CRICKET";
return this.getJdbcTemplate().queryForInt(sql);
}

}
****************************************************************
package com.venkat.model;

public class Cricket {
private int id;
private String playername;
private int runs;
private int rank;
public Cricket(int id, String playername, int runs, int rank) {
super();
this.id = id;
this.playername = playername;
this.runs = runs;
this.rank = rank;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPlayername() {
return playername;
}
public void setPlayername(String playername) {
this.playername = playername;
}
public int getRuns() {
return runs;
}
public void setRuns(int runs) {
this.runs = runs;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}

}
*****************************************************************<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="cricketDao" class="com.venkat.dao.CricketDAO">
<property name="dataSource" ref="dataSource"/>
</bean>


<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver">
</property>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe">
</property>
<property name="username" value="venkat"></property>
<property name="password" value="venkat"></property>
</bean></beans>
***************************************************************
CREATE TABLE  "CRICKET" 
   ( "ID" NUMBER, 
 "PLAYERNAME" VARCHAR2(4000), 
 "RUNS" NUMBER, 
 "RANK" NUMBER, 
  CONSTRAINT "CRICKET_PK" PRIMARY KEY ("ID") ENABLE
   )
/

Monday, April 30, 2012

Spring Named Parameter JDBC Template

We'll use the NamedParameterJdbcTemplate class to run queries with named placeholders.
SimpleJdbcTemplate is deprecated in Spring 3.1

NamedParameterJdbcTemplate is remaining and should be used for named parameter use. If you don't want to create two templates you can always call getJdbcOperations() on the NamedParameterJdbcTemplate to get access to the regular JdbcOperations interface of the JdbcTemplate.

Template class with a basic set of JDBC operations, allowing the use of named parameters rather than traditional '?' placeholders.

This class delegates to a wrapped JdbcTemplate once the substitution from named parameters to JDBC style '?' placeholders is done at execution time. It also allows for expanding a List of values to the appropriate number of placeholders.

The underlying JdbcTemplate is exposed to allow for convenient access to the traditional JdbcTemplate methods.

JDBCDemo.java

package com.venkat;

import java.util.Iterator;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.venkat.JdbcDao.JdbcDaoImpl;
import com.venkat.model.Student;

public class JDBCDemo {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args)   {
        // TODO Auto-generated method stub
       
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
          JdbcDaoImpl dao=context.getBean("jdbcDaoImpl",JdbcDaoImpl.class);
    //dao.createPersonTable();
       
         
          System.out.println(dao.getStudentCount());
          System.out.println(dao.getStudentName(121));
          System.out.println(dao.getStudentForId(121).getStudentrank());
         dao.insertStudent(new Student(444, "pradeep", 48));
         
         List<Student> list=dao.getAllStudents();
            System.out.println("Student Details...............");
         for (Iterator iterator = list.iterator(); iterator.hasNext();)
         {
            Student student = (Student) iterator.next();
            System.out.print(student.getStudentid()+"\t");
            System.out.print(student.getStudentname()+"\t");
            System.out.println(student.getStudentrank());
        }
             }

}
*************************************************************************
JdbcDaoImpl.java

package com.venkat.JdbcDao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Component;

import com.venkat.model.Student;

@Component
public class JdbcDaoImpl {
    private DataSource datasource;
    private JdbcTemplate jdbcTemplate;
    private NamedParameterJdbcTemplate  namedParameterJdbcTemplate;
   

public DataSource getDatasource() {
        return datasource;
    }


    public JdbcTemplate getJdbcTemplate() {
    return jdbcTemplate;
}


public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}

    @Autowired
    public void setDatasource(DataSource datasource) {
        this.jdbcTemplate = new JdbcTemplate(datasource);
        this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(datasource);
       
    }

public int getStudentCount()
{
    String sql="select count(*) from STUDENT";
    return jdbcTemplate.queryForInt(sql);
           
}

public String getStudentName(int studentid)
{
    String sql="select studentname from STUDENT where studentid=?";
    return jdbcTemplate.queryForObject(sql, new Object[]{studentid}, String.class);
           
}
public Student getStudentForId(int studentid)
{
    String sql="select * from STUDENT where studentid=?";
    return jdbcTemplate.queryForObject(sql, new Object[]{studentid}, new StudentMapper());
           
}
//public void insertStudent(Student student)
//{
//    String sql="insert into STUDENT (studentid,studentname,studentrank) values(?,?,?) ";
//    jdbcTemplate.update(sql,new Object[]{student.getStudentid(),student.getStudentname(),student.getStudentrank()});
//}

public void insertStudent(Student student)
{
    String sql="insert into STUDENT (studentid,studentname,studentrank) values(:studentid,:studentname,:studentrank) ";
SqlParameterSource namedParameters=new MapSqlParameterSource("studentid",student.getStudentid()).addValue("studentname", student.getStudentname()).addValue("studentrank", student.getStudentrank());
namedParameterJdbcTemplate.update(sql, namedParameters);
}

public List<Student> getAllStudents()
{
    String sql="select * from STUDENT ";
    return  jdbcTemplate.query(sql,   new StudentMapper());
           
}

public void createPersonTable()
{
    String sql="create table Person (id Number(3),name varchar2(12))";
    jdbcTemplate.execute(sql);
}
private static final class StudentMapper implements RowMapper<Student>
{

    @Override
    public Student mapRow(ResultSet resultset, int rowNum) throws SQLException {
        Student s=new Student();
        s.setStudentid(resultset.getInt("studentid"));
        s.setStudentname(resultset.getString("studentname"));
        s.setStudentrank(resultset.getInt("studentrank"));
       
        return s;
    }
   
   
   
}
}

***********************************************************************
package com.venkat.model;

public class Student {
   
    private int studentid;
    private String studentname;
    private int studentrank;
    public int getStudentid() {
        return studentid;
    }
    public void setStudentid(int studentid) {
        this.studentid = studentid;
    }
    public String getStudentname() {
        return studentname;
    }
    public void setStudentname(String studentname) {
        this.studentname = studentname;
    }
    public int getStudentrank() {
        return studentrank;
    }
    public void setStudentrank(int studentrank) {
        this.studentrank = studentrank;
    }
    public Student(int studentid, String studentname, int studentrank) {
        super();
        this.studentid = studentid;
        this.studentname = studentname;
        this.studentrank = studentrank;
    }
    public Student() {
        // TODO Auto-generated constructor stub
    }
   

}
*****************************************************************
<?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:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config/>

<context:component-scan base-package="com.venkat"></context:component-scan>



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

Sunday, April 29, 2012

Performing Write Operations with JdbcTemplate

We'll now implement some database write operations. We'll write a DAO method to update a value in the database, as well as use the execute() method to run a DDL SQL query.



package com.venkat;


import java.util.Iterator;
import java.util.List;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.venkat.JdbcDao.JdbcDaoImpl;
import com.venkat.model.Student;


public class JDBCDemo {


/**
* @param args
* @throws Exception 
*/
public static void main(String[] args)   {
// TODO Auto-generated method stub

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
 JdbcDaoImpl dao=context.getBean("jdbcDaoImpl",JdbcDaoImpl.class);
//dao.createPersonTable();

 
 System.out.println(dao.getStudentCount());
 System.out.println(dao.getStudentName(121));
 System.out.println(dao.getStudentForId(121).getStudentrank());
dao.insertStudent(new Student(345, "Sandeep", 8));
 
List<Student> list=dao.getAllStudents();
System.out.println("Student Details...............");
for (Iterator iterator = list.iterator(); iterator.hasNext();) 
{
Student student = (Student) iterator.next();
System.out.print(student.getStudentid()+"\t");
System.out.print(student.getStudentname()+"\t");
System.out.println(student.getStudentrank());
}
}


}
*************************************************************************
package com.venkat.JdbcDao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.venkat.model.Student;

@Component
public class JdbcDaoImpl {
private DataSource datasource;
private JdbcTemplate jdbcTemplate;

public DataSource getDatasource() {
return datasource;
}


public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}


public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

@Autowired
public void setDatasource(DataSource datasource) {
this.jdbcTemplate = new JdbcTemplate(datasource);
}

public int getStudentCount()
{
String sql="select count(*) from STUDENT";
return jdbcTemplate.queryForInt(sql);
}

public String getStudentName(int studentid)
{
String sql="select studentname from STUDENT where studentid=?";
return jdbcTemplate.queryForObject(sql, new Object[]{studentid}, String.class);
}
public Student getStudentForId(int studentid)
{
String sql="select * from STUDENT where studentid=?";
return jdbcTemplate.queryForObject(sql, new Object[]{studentid}, new StudentMapper());
}
public void insertStudent(Student student)
{
String sql="insert into STUDENT (studentid,studentname,studentrank) values(?,?,?) ";
jdbcTemplate.update(sql,new Object[]{student.getStudentid(),student.getStudentname(),student.getStudentrank()});
}

public List<Student> getAllStudents()
{
String sql="select * from STUDENT ";
return  jdbcTemplate.query(sql,   new StudentMapper());
}

public void createPersonTable()
{
String sql="create table Person (id Number(3),name varchar2(12))";
jdbcTemplate.execute(sql);
}
private static final class StudentMapper implements RowMapper<Student>
{

@Override
public Student mapRow(ResultSet resultset, int rowNum) throws SQLException {
Student s=new Student();
s.setStudentid(resultset.getInt("studentid"));
s.setStudentname(resultset.getString("studentname"));
s.setStudentrank(resultset.getInt("studentrank"));
return s;
}
}
}
************************************************************************
package com.venkat.model;

public class Student {
private int studentid;
private String studentname;
private int studentrank;
public int getStudentid() {
return studentid;
}
public void setStudentid(int studentid) {
this.studentid = studentid;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getStudentrank() {
return studentrank;
}
public void setStudentrank(int studentrank) {
this.studentrank = studentrank;
}
public Student(int studentid, String studentname, int studentrank) {
super();
this.studentid = studentid;
this.studentname = studentname;
this.studentrank = studentrank;
}
public Student() {
// TODO Auto-generated constructor stub
}

}
************************************************************
<?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:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config/>

<context:component-scan base-package="com.venkat"></context:component-scan>



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

Spring JDBC Implementing RowMapper

In this tutorial, we implement a custom RowMapper class to map our domain objects. We then use this class to write fetch methods that return custom model objects.



 <Student> List<Student> org.springframework.jdbc.core.JdbcTemplate.query(String sql, RowMapper<Student> rowMapper) throws DataAccessException
query
public <T> List<T> query(String sql,
                         RowMapper<T> rowMapper)
              throws DataAccessException
Description copied from interface: JdbcOperations 
Execute a query given static SQL, mapping each row to a Java object via a RowMapper. 
Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded query method with null as argument array. 




Specified by:
query in interface JdbcOperations
Parameters:
sql - SQL query to execute
rowMapper - object that will map one object per row 
Returns:
the result List, containing mapped objects 
Throws: 
DataAccessException - if there is any problem executing the query
See Also:
JdbcOperations.query(String, Object[], RowMapper)
--------------------------------------------------------------------------------
An interface used by JdbcTemplate for mapping rows of a ResultSet on a per-row basis. Implementations of this interface perform the actual work of mapping each row to a result object, but don't need to worry about exception handling. SQLExceptions will be caught and handled by the calling JdbcTemplate. 

Typically used either for JdbcTemplate's query methods or for out parameters of stored procedures. RowMapper objects are typically stateless and thus reusable; they are an ideal choice for implementing row-mapping logic in a single place. 

Alternatively, consider subclassing MappingSqlQuery from the jdbc.object package: Instead of working with separate JdbcTemplate and RowMapper objects, you can build executable query objects (containing row-mapping logic) in that style. 
****************************************************************************
package com.venkat;

import java.util.Iterator;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.venkat.JdbcDao.JdbcDaoImpl;
import com.venkat.model.Student;

public class JDBCDemo {

/**
* @param args
* @throws Exception 
*/
public static void main(String[] args)   {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
 JdbcDaoImpl dao=context.getBean("jdbcDaoImpl",JdbcDaoImpl.class);
 System.out.println(dao.getStudentCount());
 System.out.println(dao.getStudentName(121));
 System.out.println(dao.getStudentForId(121).getStudentrank());
List<Student> list=dao.getAllStudents();
System.out.println("Student Details...............");
for (Iterator iterator = list.iterator(); iterator.hasNext();) 
{
Student student = (Student) iterator.next();
System.out.print(student.getStudentid()+"\t");
System.out.print(student.getStudentname()+"\t");
System.out.println(student.getStudentrank());
}
}

}
******************************************************************
package com.venkat.JdbcDao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import com.venkat.model.Student;

@Component
public class JdbcDaoImpl {
private DataSource datasource;
private JdbcTemplate jdbcTemplate;

public DataSource getDatasource() {
return datasource;
}


public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}


public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

@Autowired
public void setDatasource(DataSource datasource) {
this.jdbcTemplate = new JdbcTemplate(datasource);
}

public int getStudentCount()
{
String sql="select count(*) from STUDENT";
return jdbcTemplate.queryForInt(sql);
}

public String getStudentName(int studentid)
{
String sql="select studentname from STUDENT where studentid=?";
return jdbcTemplate.queryForObject(sql, new Object[]{studentid}, String.class);
}
public Student getStudentForId(int studentid)
{
String sql="select * from STUDENT where studentid=?";
return jdbcTemplate.queryForObject(sql, new Object[]{studentid}, new StudentMapper());
}
public List<Student> getAllStudents()
{
String sql="select * from STUDENT ";
return  jdbcTemplate.query(sql,   new StudentMapper());
}
private static final class StudentMapper implements RowMapper<Student>
{

@Override
public Student mapRow(ResultSet resultset, int rowNum) throws SQLException {
Student s=new Student();
s.setStudentid(resultset.getInt("studentid"));
s.setStudentname(resultset.getString("studentname"));
s.setStudentrank(resultset.getInt("studentrank"));
return s;
}
}
}
********************************************************************
package com.venkat.model;

public class Student {
private int studentid;
private String studentname;
private int studentrank;
public int getStudentid() {
return studentid;
}
public void setStudentid(int studentid) {
this.studentid = studentid;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getStudentrank() {
return studentrank;
}
public void setStudentrank(int studentrank) {
this.studentrank = studentrank;
}
public Student(int studentid, String studentname, int studentrank) {
super();
this.studentid = studentid;
this.studentname = studentname;
this.studentrank = studentrank;
}
public Student() {
// TODO Auto-generated constructor stub
}

}
*******************************************************************
<?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:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config/>

<context:component-scan base-package="com.venkat"></context:component-scan>



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

SPRING Returning Other Datatypes from JdbcTemplate

We returned an integer datatype result from our query in the previous tutorial. In this tutorial, we'll learn how to return other datatypes. We'll implement a method that returns a String query output.



 int org.springframework.jdbc.core.JdbcTemplate.queryForInt(String sql) throws DataAccessException
queryForInt
public int queryForInt(String sql)
                throws DataAccessException
Description copied from interface: JdbcOperations 
Execute a query that results in an int value, given static SQL. 
Uses a JDBC Statement, not a PreparedStatement. If you want to execute a static query with a PreparedStatement, use the overloaded queryForInt method with null as argument array. 


This method is useful for running static SQL with a known outcome. The query is expected to be a single row/single column query that results in an int value. 




Specified by:
queryForInt in interface JdbcOperations
Parameters:
sql - SQL query to execute 
Returns:
the int value, or 0 in case of SQL NULL 
Throws: 
IncorrectResultSizeDataAccessException - if the query does not return exactly one row, or does not return exactly one column in that row 
DataAccessException - if there is any problem executing the query
See Also:
JdbcOperations.queryForInt(String, Object[])



****************************************************************


 <String> String org.springframework.jdbc.core.JdbcTemplate.queryForObject(String sql, Object[] args, Class<String> requiredType) throws DataAccessException






queryForObject
public <T> T queryForObject(String sql,
                            Object[] args,
                            Class<T> requiredType)
                 throws DataAccessException
Description copied from interface: JdbcOperations 
Query given SQL to create a prepared statement from SQL and a list of arguments to bind to the query, expecting a result object. 
The query is expected to be a single row/single column query; the returned result will be directly mapped to the corresponding object type. 




Specified by:
queryForObject in interface JdbcOperations
Parameters:
sql - SQL query to execute
args - arguments to bind to the query (leaving it to the PreparedStatement to guess the corresponding SQL type); may also contain SqlParameterValue objects which indicate not only the argument value but also the SQL type and optionally the scale
requiredType - the type that the result object is expected to match 
Returns:
the result object of the required type, or null in case of SQL NULL 
Throws: 
IncorrectResultSizeDataAccessException - if the query does not return exactly one row, or does not return exactly one column in that row 
DataAccessException - if the query fails
See Also:
JdbcOperations.queryForObject(String, Class)
****************************************************************************

package com.venkat;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import com.venkat.JdbcDao.JdbcDaoImpl;


public class JDBCDemo {


/**
* @param args
* @throws Exception 
*/
public static void main(String[] args)   {
// TODO Auto-generated method stub

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
 JdbcDaoImpl dao=context.getBean("jdbcDaoImpl",JdbcDaoImpl.class);

 System.out.println(dao.getStudentCount());
 System.out.println(dao.getStudentName(121));
}


}
************************************************************************
package com.venkat.JdbcDao;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class JdbcDaoImpl {
private DataSource datasource;
private JdbcTemplate jdbcTemplate;

public DataSource getDatasource() {
return datasource;
}


public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}


public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

@Autowired
public void setDatasource(DataSource datasource) {
this.jdbcTemplate = new JdbcTemplate(datasource);
}

public int getStudentCount()
{
String sql="select count(*) from STUDENT";
return jdbcTemplate.queryForInt(sql);
}

public String getStudentName(int studentid)
{
String sql="select studentname from STUDENT where studentid=?";
return jdbcTemplate.queryForObject(sql, new Object[]{studentid}, String.class);
}
}
**************************************************************************
package com.venkat.model;

public class Student {
private int studentid;
private String studentname;
private int studentrank;
public int getStudentid() {
return studentid;
}
public void setStudentid(int studentid) {
this.studentid = studentid;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public int getStudentrank() {
return studentrank;
}
public void setStudentrank(int studentrank) {
this.studentrank = studentrank;
}
public Student(int studentid, String studentname, int studentrank) {
super();
this.studentid = studentid;
this.studentname = studentname;
this.studentrank = studentrank;
}

}
************************************************************************
<?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:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<context:annotation-config/>

<context:component-scan base-package="com.venkat"></context:component-scan>



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