Showing posts with label JDBCTemplate. Show all posts
Showing posts with label JDBCTemplate. Show all posts

Spring: Data access with JDBCTemplate

Spring provides a template class called JdbcTemplate that makes it easy to work with SQL relational databases and JDBC. Most JDBC code is mired in resource acquisition, connection management, exception handling, and general error checking that is wholly unrelated to what the code is meant to achieve. The JdbcTemplate takes care of all of that for you. All you have to do is focus on the task at hand.

In our earlier tutorial we have seen about Spring JDBC with simple example. Lets take same example for this tutorial and will implement separate method called insertByJDBCTemplate() which uses Spring JDBCTemplate to insert a record.

pom.xml remains same

Employee.java remains same

EmpDao.java

package com.app.dao;

import com.app.model.Employee;

public interface EmpDao {

 public void insert(Employee emp);
 public void insertByJDBCTemplate(Employee emp);
 
}


EmpDaoImpl.java

package com.app.dao;

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

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.app.model.Employee;

public class EmpDaoImpl implements EmpDao {

 
 private DataSource dataSource;
 private JdbcTemplate jdbcTemplate;
 
 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }
  
 public void insert(Employee emp) {
 
  String query = "INSERT INTO employee (id, empname, designation) VALUES (?, ?, ?)";
  Connection con = null;
 
  try {
   con = dataSource.getConnection();
   PreparedStatement ps = con.prepareStatement(query);
   ps.setInt(1, emp.getId());
   ps.setString(2, emp.getEmpName());
   ps.setString(3, emp.getDesignation());
   ps.executeUpdate();
   ps.close();
 
  } catch (SQLException e) {
   throw new RuntimeException(e);
 
  } finally {
   if (con != null) {
    try {
     con.close();
    } catch (SQLException e) {}
   }
  }  
 }
 
 
 
 public void insertByJDBCTemplate(Employee emp) {
  
  String query = "INSERT INTO employee (id, empname, designation) VALUES (?, ?, ?)";
  
  jdbcTemplate = new JdbcTemplate(dataSource);
   
  jdbcTemplate.update(query, new Object[] { emp.getId(), emp.getEmpName(), emp.getDesignation() });
 }
}


MyTestClass.java

package com.app;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.app.dao.EmpDao;
import com.app.model.Employee;

public class MyTestClass {

 public static void main(String[] args) {
  
  ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring-jdbc.xml");

  EmpDao object = appContext.getBean(EmpDao.class);
  
  Employee emp = new Employee(10011, "Steve", "CEO");
  
  //object.insert(emp);
  object.insertByJDBCTemplate(emp);
  
  appContext.close();
 }
}


OUTPUT:

Spring: Data access with JDBCTemplate