22.SpringJdbc : PreparedStatement Example

PreparedStatement Insertion:
·         We can insert data by using preparedStatement in Spring
·         For this we use public T execute(String sql,PreparedStatementCallback<T>);  
·         Here PreparedStatementCallback is an Interface
·         It has one method public T doInPreparedStatement(PreparedStatement ps)throws SQLException, DataAccessException 
·         We have to provide implement for above method in order to deal with PreparedStatement
Example: StudentBo.java, s.xml are same as previous Example

///StudentDAO.java
package dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;

import bo.StudentBo;


public class StudentDAO {
      
 private JdbcTemplate template;

public JdbcTemplate getTemplate() {
       return template;
}

public void setTemplate(JdbcTemplate template) {
       this.template = template;
}

public boolean save(final StudentBo bo){
       String qry = "INSERT INTO student VALUES (?,?,?)";
       System.out.println("Qry--> "+qry);
       return template.execute(qry, new PreparedStatementCallback<Boolean>() {
              @Override
              public Boolean doInPreparedStatement(PreparedStatement ps)
                           throws SQLException, DataAccessException {
                     // TODO Auto-generated method stub
                     ps.setInt(1, bo.getSno());
                     ps.setString(2, bo.getName());
                     ps.setString(3, bo.getAddress());              
                     return ps.execute();
              }
             
       });
      
}

}

//Main.java
package main;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import bo.StudentBo;

import dao.StudentDAO;

public class Main {
       public static void main(String[] args) {
               
              BeanFactory factory = new ClassPathXmlApplicationContext("res/s.xml");
              StudentDAO dao = (StudentDAO) factory.getBean("dao");
              StudentBo bo = new StudentBo();
              bo.setSno(4);
              bo.setName("SURYA");
              bo.setAddress("CHENNAI");
              System.out.println("SAVING : "+dao.save(bo));
       }
}


Post a Comment

Thank You

Previous Post Next Post