哈喽,大家好,很高兴大家能看到这篇粗浅的博客,在这鸡年即将到来的时刻,提前给大家拜个早年,祝大家新的一年里“万行code丛中过,片叶bug不沾身”。今天给大家介绍一下spring结合jdbcTemplate进行数据库的访问操作。
前一篇文章,简要说明了spring与jdbc进行数据操作的过程,有很多沉重冗余的代码,在JdbcTemplate的帮助下,你会省下很多重复的代码,因为JdbcTemplate会帮你自动处理。本篇文章继续用上一篇的cutomer表做示例说明。
1.通过eclipse创建maven项目,目录结构如下:

2.项目依赖pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>spring-jdbcTemplate</groupId><artifactId>spring-jdbcTemplate</artifactId><version>0.0.1-SNAPSHOT</version><dependencies><!-- Spring Core --><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>4.2.1.RELEASE</version></dependency><!-- Spring context --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>4.2.1.RELEASE</version></dependency><!-- Spring JDBC --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>4.2.1.RELEASE</version></dependency><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency><!-- mysql驱动包 -->  <dependency>  <groupId>mysql</groupId>  <artifactId>mysql-connector-java</artifactId>  <version>5.1.29</version>  </dependency>  </dependencies>
</project>
3.DAO层
这里的dao层与jdbc的dao层是最大的不同之处,jdbcTemplate对象封住了很多方法,你只需要专注自己的业务逻辑,而不是像jdbc那样冗余的代码。异常也不需要你来补货,而是jdbctemplate会自动帮你处理。
package org.thinkingingis.dao;import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;import javax.sql.DataSource;import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.thinkingingis.model.Customer;public class JdbcTemplateCustomerDAO {private JdbcTemplate jdbcTemplate;public void setDataSource(DataSource dataSource) {this.jdbcTemplate = new JdbcTemplate(dataSource);}//统计该表所有记录数public int CountRowNumber(){int rowCount = this.jdbcTemplate.queryForObject("select count(*) from customer", Integer.class);return rowCount;}//根据cust_id查customer对象public Customer findCustomerById(int id){String sql = "select * from customer where cust_id = ?";Customer customer = this.jdbcTemplate.queryForObject(sql, new Object[]{id}, new RowMapper<Customer>(){public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {Customer customers = new Customer();customers.setId(rs.getInt("cust_id"));customers.setName(rs.getString("name"));customers.setAge(rs.getInt("age"));return customers;}});return customer;}//根据id获得namepublic String getCustomerNameById(int id){String strName = this.jdbcTemplate.queryForObject("select name from customer where cust_id = ?", new Object[]{id}, String.class);return strName;}//查询所有表数据public List<Customer> findAllCustomer(){return this.jdbcTemplate.query("select * from customer", new CustomerMapper());}public static final class CustomerMapper implements RowMapper<Customer>{public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {Customer customer = new Customer();customer.setId(rs.getInt("cust_id"));customer.setName(rs.getString("name"));customer.setAge(rs.getInt("age"));return customer;}}//更新操作public void updateCustomerNameById(String name, int id){this.jdbcTemplate.update("update customer set name = ? where cust_id = ?", name, id);}}
4.通过xml文件方式配置数据源与bean
这次将数据源与jdbcTemplateCustomerDAO写在一个xml文件中
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsd"><bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/springmvcjdbc" /><property name="username" value="root" /><property name="password" value="123456" /></bean><bean id="jdbcTemplateCustomerDAO" class="org.thinkingingis.dao.JdbcTemplateCustomerDAO"><property name="dataSource" ref="dataSource"/></bean></beans>
5.controller层 App.java
package org.thinkingingis.controller;import java.util.List;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.thinkingingis.dao.JdbcTemplateCustomerDAO;
import org.thinkingingis.model.Customer;public class App {public static void main(String[] args){ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");JdbcTemplateCustomerDAO jdbcTemplateCustomerDao = (JdbcTemplateCustomerDAO) context.getBean("jdbcTemplateCustomerDAO");int rowCount = jdbcTemplateCustomerDao.CountRowNumber();System.out.println(rowCount);jdbcTemplateCustomerDao.updateCustomerNameById("CAN", 4);Customer customer = jdbcTemplateCustomerDao.findCustomerById(1);System.out.println("name: " + customer.getName());String name = jdbcTemplateCustomerDao.getCustomerNameById(2);System.out.println("id 为2 的 name: " + name);List<Customer> lists = jdbcTemplateCustomerDao.findAllCustomer();for(int i=0; i<lists.size(); i++){System.out.println(lists.get(i).getId() + "--" + lists.get(i).getName() + "--" + lists.get(i).getAge());}}
}
6结果截图

spring与jdbctemplate访问数据就完成啦,值得注意的是相比jdbc方式,他会省去你很多时间去写jdbc代码。

(如遇到问题,请留言给作者,以便共同探讨gis知识。thinkingingis@qq.com)

Wechat公众号:ThinkingInGIS

欢迎大家关注:)

Spring 数据访问那些事儿(二)Spring + JdbcTemplate相关推荐

  1. Spring 数据访问那些事儿(一)spring + jdbc

    从本篇文章开始,将会陆续为大家介绍一些spring访问数据的方式,从简单直接的JDBC到JdbcTemplate,再到一些复杂的ORM框架(如mybatis.hibernate).每篇文章都跟着一个简 ...

  2. 【Spring 数据访问终篇】Spring + Hibernate + Mysql

    说来惭愧,数月没有更新博客,今天带来spring访问数据的最终篇,spring + hibernate. 本篇文章将用maven创建一个简答的java项目,并结合spring框架中的hibernate ...

  3. 转载:使用Spring进行数据访问(Data Access With Spring)

    Table of Contents 1.1. 统一的数据访问异常层次体系(Consistent Exception Hierarchy In Spring) 1.1.1. DAO模式的背景(Backg ...

  4. 打造自己的数据访问层(二)

    上一篇打造自己的数据访问层(一)中,我们已了解了.NET对数据库操作的基本原理,并就Ado.net对象的使用提出了几点疑问: 1.如何由系统来判断数据库型. 2.如何消除这些重复代码. 而上篇中也提出 ...

  5. Spring源码系列(十二)Spring创建Bean的过程(二)

    1.写在前面 上篇博客主要Spring在创建Bean的时候,第一次调用的Bean的后置处理器的过程,同时笔者也打算将整个Spring创建的Bean的过程,通过这个系列,将Bean的创建过程给讲清楚,废 ...

  6. spring aop实现过程之二Spring AOP中拦截器链

    1.开始步骤--获取AopProxy主流程 ProxyCreatorSupport.java /*** Subclasses should call this to get a new AOP pro ...

  7. 使用Spring JDBC进行数据访问 (JdbcTemplate/NamedParameterJdbcTemplate/SimpleJdbcTemplate/SimpleJdbcCall/Stor)

    http://www.cnblogs.com/webcc/archive/2012/04/11/2442680.html 使用Spring JDBC进行数据访问 11.1. 简介 Spring JDB ...

  8. Spring - Java/J2EE Application Framework 应用框架 第 11 章 使用ORM工具进行数据访问

    第 11 章 使用ORM工具进行数据访问 11.1. 简介 Spring在资源管理,DAO实现支持以及实物策略等方面提供了与Hibernate, JDO和iBATIS SQL映射的集成. 对Hiber ...

  9. Spring - Java/J2EE Application Framework 应用框架 第 10 章 使用JDBC进行数据访问

    第 10 章 使用JDBC进行数据访问 10.1. 简介 Spring提供的JDBC抽象框架由core, datasource,object和support四个不同的包组成. 就和它名字的暗示一样,o ...

最新文章

  1. 用Python解析AndroidManifest.xml文件找MainActivity
  2. Python入门-day1变量和简单数据类型
  3. 【测试点分析】1035 Password (20 分)
  4. 组播,单播,广播,多播,泛洪的概念
  5. cvtcolor python opencv_二值分析 | OpenCV + skimage如何提取中心线
  6. 干支纪年法简便算法_民间玄学:那些年我理解的何谓“天干”,“地支”,“干支”...
  7. PyTorch框架学习十六——正则化与Dropout
  8. CodeSmith将模板文件批量生成文件的方法
  9. [转载] Python 学习笔记 迭代器和生成器
  10. 2.SRE:Google运维解密 --- Google 生产环境:SRE 视角
  11. C#入门详解(10)
  12. 转载]转如何理解 File's Owner 与 First Responder
  13. 固态硬盘SSD的SLC与MLC和TLC三者的区别
  14. 【第八周】程序设计方法学
  15. 数学方法论的含义和研究意义
  16. 交叉25码是什么条码
  17. python如何做一个财务报表_用python帮财务小姐姐自动生成财务报表
  18. [渝粤教育] 南通大学 大学计算机信息技术基础 参考 资料
  19. 地理学中的经典统计分析方法
  20. 【日成海外营销】如何利用TikTok进行红人营销?

热门文章

  1. [codevs 1237] 餐巾计划问题
  2. UOJ #455 [UER #8]雪灾与外卖 (贪心、模拟费用流)
  3. python类方法继承_对python中类的继承与方法重写介绍
  4. java调用easyxml接口_【技术教程】如何通过Java程序调用RTSP拉流协议视频平台EasyNVR程序接口?...
  5. python数据库哪个好_终于明了python用什么数据库好
  6. next_permutation(start,end)
  7. ASP.NET Core 2.2 基础知识(十四) WebAPI Action返回类型(未完待续)
  8. 为 Nginx 创建 windows 服务自启动
  9. cmd编译运行Java文件详解
  10. Cracking the coding interview--Q1.4