Spring Jdbctemplate示例

时间:2020-02-23 14:35:53  来源:igfitidea点击:

在本教程中,我们将看到Spring Jdbctemplate示例。

Spring JDBCTemplate用于方便连接到数据库并执行查询。
它在内部使用JDBC代码,但为我们提供API,因此我们不必编写锅炉板代码。
在执行查询以创建连接,创建语句,关闭连接等后,我们没有写入太多代码。

让我们在简单的例子的帮助下理解:

让我们说要将Country对象保存到数据库。
如果我们想使用正常的JDBC API编写它,则必须使用以下代码:

public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (?,?,?)";
  Connection con = null;
  PreparedStatement ps = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setInt(1, country.getId());
   ps.setString(2, country.getCountryName());
   ps.setLong(3, country.getPopulation());
   int out = ps.executeUpdate();
   if (out != 0) {
    System.out.println("Country saved with country=" + country.getCountryName());
   } else
    System.out.println("Country save failed with country=" + country.getCountryName());
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  return country;
 }

如果使用Spring Jdbctemplate进行相同操作,则需要使用以下代码:

public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (?,?,?)";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
  Object[] args = new Object[] { country.getId(), country.getCountryName(), country.getPopulation() };
  int status = jdbcTemplate.update(query, args);
  if (status != 0) {
   System.out.println("Country saved with country=" + country.getCountryName());
  } else
   System.out.println("Country save failed with country=" + country.getCountryName());
  return country;
 }

如果我们观察到上面的代码,我们可以轻松地看到我们需要使用Spring JDBCtemplate编写非常小的代码,并且我们也不需要进行异常处理

使用普通JDBC API的Spring示例:

使用以下代码在MySQL数据库中创建国家表:

CREATE TABLE COUNTRY
(
   id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
   countryName varchar(100) NOT NULL,
   population int NOT NULL
)
;

我们将使用Country Table进行查询和更新数据库中的值。

允许首先创建我们的bean类country.java

package org.igi.theitroad.model;
 
/*
 * This is our model class and it corresponds to Country table in database
 */
 
public class Country{
 
 int id;
 String countryName; 
 long population;
 
 public Country() {
  super();
 }
 public Country(int i, String countryName,long population) {
  super();
  this.id = i;
  this.countryName = countryName;
  this.population=population;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 }
 @Override
 public String toString() {
  return "Country [id=" + id + ", countryName=" + countryName + ", population=" + population + "]";
 } 
 
}

创建一个DAO类CountryDao.java,它将拥有数据库操作的所有方法。

package org.igi.theitroad.dao;
 
import java.util.List;
 
import org.igi.theitroad.model.Country;
 
public interface CountryDAO {
 
 List getAllCountries();
 
 Country getCountry(int id);
 
 Country addCountry(Country country);
 
 void updateCountry(Country country);
 
 void deleteCountry(int id);
 
}

使用普通JDBC API创建DAO实现上述接口。

package org.igi.theitroad.dao;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
 
import javax.sql.DataSource;
 
import org.igi.theitroad.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
@Repository("countryDAO")
public class CountryDAOImpl implements CountryDAO {
 
 @Autowired
 private DataSource dataSource;
 
 @Override
 public List getAllCountries() {
  String query = "select id, countryname, population from Country";
  List countryList = new ArrayList();
  Connection con = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   rs = ps.executeQuery();
   while (rs.next()) {
    Country country = new Country();
    country.setId(rs.getInt("id"));
    country.setCountryName(rs.getString("countryname"));
    country.setPopulation(rs.getLong("population"));
    countryList.add(country);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    rs.close();
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  return countryList;
 }
 
 @Override
 public Country getCountry(int id) {
  String query = "select countryname, population from Country where id = ?";
  Country country = null;
  Connection con = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setInt(1, id);
   rs = ps.executeQuery();
   if (rs.next()) {
    country = new Country();
    country.setId(id);
    country.setCountryName(rs.getString("countryname"));
    country.setPopulation(rs.getLong("population"));
    System.out.println("Country Found::" + country);
   } else {
    System.out.println("No Country found with id=" + id);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    rs.close();
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  return country;
 }
 
 @Override
 public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (?,?,?)";
  Connection con = null;
  PreparedStatement ps = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setInt(1, country.getId());
   ps.setString(2, country.getCountryName());
   ps.setLong(3, country.getPopulation());
   int out = ps.executeUpdate();
   if (out != 0) {
    System.out.println("Country saved with country=" + country.getCountryName());
   } else
    System.out.println("Country save failed with country=" + country.getCountryName());
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  return country;
 }
 
 @Override
 public void updateCountry(Country country) {
  String query = "update Country set countryname=?, population=? where id=?";
  Connection con = null;
  PreparedStatement ps = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setString(1, country.getCountryName());
   ps.setLong(2, country.getPopulation());
   ps.setInt(3, country.getId());
   int out = ps.executeUpdate();
   if (out != 0) {
    System.out.println("Country updated with country=" + country.getCountryName());
   } else
    System.out.println("No Country found with country=" + country.getCountryName());
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }
 
 public void deleteCountry(int id) {
  String query = "delete from Country where id=?";
  Connection con = null;
  PreparedStatement ps = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setInt(1, id);
   int out = ps.executeUpdate();
   if (out != 0) {
    System.out.println("Country deleted with id=" + id);
   } else
    System.out.println("No Country found with id=" + id);
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }
}

创建ApplicationContext.xml如下所示

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
 
 <context:annotation-config 
 <beans:bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" 
  <beans:property name="url"
   value="jdbc:mysql://localhost:3306/CountryData" 
  <beans:property name="username" value="root" 
  <beans:property name="password" value="" 
 </beans:bean>
 <context:component-scan base-package="org.igi.theitroad" 
</beans:beans>

在连接详细信息上配置数据源,DataSource Bean将在CountryDaoimpl中自动。
创建名为SpringApplicationMain.java的主类如下所示

package org.igi.theitroad.main;
 
import java.util.List;
 
import org.igi.theitroad.dao.CountryDAO;
import org.igi.theitroad.model.Country;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class SpringApplicationMain {
 public static void main(String[] args) {
 
  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  CountryDAO countryDao = (CountryDAO) context.getBean("countryDAO");
 
  Country countryUSA = new Country();
  countryUSA.setCountryName("USA");
  countryUSA.setPopulation(10000);
  
  Country countryNetherlands = new Country();
  countryNetherlands.setCountryName("Netherlands");
  countryNetherlands.setPopulation(20000);
  
  Country countryChina = new Country();
  countryChina.setCountryName("China");
  countryChina.setPopulation(30000);
  
  Country countryBhutan = new Country();
  countryBhutan.setCountryName("Bhutan");
  countryBhutan.setPopulation(5000);
  
 
  //Add Country
  countryDao.addCountry(countryUSA);
  countryDao.addCountry(countryNetherlands);
  countryDao.addCountry(countryChina);
  countryDao.addCountry(countryBhutan);
  //Read
  Country countryRead = countryDao.getCountry(3);
  System.out.println("Getting country with ID 3::" + countryRead.getCountryName());
 
  //Update
  countryRead.setPopulation(40000);
  countryDao.updateCountry(countryRead);
 
  //Get All
  List countryList = countryDao.getAllCountries();
  System.out.println(countryList);
 
  //Delete
  countryDao.deleteCountry(4);
 
  System.out.println("We are done with all operations");
 }
}

运行上面的程序时,我们将得到以下输出:

Aug 28, 2015 11:01:20 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@71881149: startup date [Sun Aug 28 23:01:20 IST 2015]; root of context hierarchy
Aug 28, 2015 11:01:21 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Aug 28, 2015 11:01:21 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Country saved with country=USA
Country saved with country=Netherlands
Country saved with country=China
Country saved with country=Bhutan
Country Found::Country [id=3, countryName=China, population=30000]
Getting country with ID 3::China
Country updated with country=China
[Country [id=1, countryName=USA, population=10000], Country [id=2, countryName=Netherlands, population=20000], Country [id=3, countryName=China, population=40000], Country [id=4, countryName=Bhutan, population=5000]]
Country deleted with id=4
We are done with all operations

正如我们在CountryDaoimpl所看到的那样,我们需要编写大量代码来处理连接,例外等。

Spring Jdbctemplate示例:

现在替换在CountryDaoimpl.java之上,带有Spring JDbctemplate示例。

package org.igi.theitroad.dao;
 
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
import javax.sql.DataSource;
 
import org.igi.theitroad.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
 
@Repository("countryDAO")
public class SpringJDBCTemplateExample implements CountryDAO {
 
 @Autowired
 private DataSource dataSource;
 
 @Override
 public List getAllCountries() {
  String query = "select id, countryname, population from Country";
  List countryList = new ArrayList();
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
 
  List<Map<String, Object>> countryRows = jdbcTemplate.queryForList(query);
 
  for (Map<String, Object> countryRow : countryRows) {
   Country country = new Country();
   country.setId(Integer.parseInt(String.valueOf(countryRow.get("id"))));
   country.setCountryName(String.valueOf(countryRow.get("countryName")));
   country.setPopulation((Integer)countryRow.get("population"));
   countryList.add(country);
  }
 
  return countryList;
 }
 
 @Override
 public Country getCountry(int id) {
  String query = "select id,countryname, population from Country where id = ?";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
 
  //using RowMapper anonymous class, we can create a separate RowMapper
  //for reuse
  Country country = jdbcTemplate.queryForObject(query, new Object[] {id}, new RowMapper() {
 
   @Override
   public Country mapRow(ResultSet rs, int rowNum) throws SQLException {
    Country country = new Country();
    country.setId(rs.getInt("id"));
    country.setCountryName(rs.getString("countryname"));
    country.setPopulation(rs.getLong("population"));
    return country;
   }
  });
 
  return country;
 }
 
 @Override
 public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (?,?,?)";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
 
  Object[] args = new Object[] { country.getId(), country.getCountryName(), country.getPopulation() };
 
  int status = jdbcTemplate.update(query, args);
 
  if (status != 0) {
   System.out.println("Country saved with country=" + country.getCountryName());
  } else
   System.out.println("Country save failed with country=" + country.getCountryName());
 
  return country;
 }
 
 @Override
 public void updateCountry(Country country) {
  String query = "update Country set countryname=?, population=? where id=?";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
 
  Object[] args = new Object[] { country.getId(), country.getCountryName(), country.getPopulation() };
 
  int status = jdbcTemplate.update(query, args);
  if (status != 0) {
   System.out.println("Country updated with country=" + country.getCountryName());
  } else
   System.out.println("No Country found with country=" + country.getCountryName());
 }
 
 @Override
 public void deleteCountry(int id) {
  String query = "delete from Country where id=?";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
 
  int status = jdbcTemplate.update(query, id);
  if (status != 0) {
   System.out.println("Country deleted with id=" + id);
  } else
   System.out.println("No Country found with id=" + id);
 }
 
}

正如我们所看到的,我们需要使用SpringJdbctemplate编写非常小的代码。
jdbctemplate.update(查询,args):此方法用于在数据库中添加或者更新。
object [] args是Arguments数组对应?
在查询中。
jdbctemplate.queryforobject(查询,新对象[] {id},new towmapper():我们使用了rowmapper和overriden maprows方法,将结果从结果集设置为国家对象。