前言

本篇紧接着spring入门详细教程(三),建议阅读本篇前,先阅读第一篇,第二篇以及第三篇。链接如下:

Spring入门详细教程(一) https://www.cnblogs.com/jichi/p/10165538.html

Spring入门详细教程(二) https://www.cnblogs.com/jichi/p/10176601.html

Spring入门详细教程(三) https://www.cnblogs.com/jichi/p/10177004.html

本篇主要讲解spring的jdbcTemplate相关。

一、spring整合jdbc继承jdbcdaosupport的方式

1、导入所需jar包。

除了之前介绍的spring的基础包,还需要导入数据库连接池包,jdbc驱动包,spring的jdbc包,spring的事务。

2、书写dao层代码。

public class UserDaoImpl extends JdbcDaoSupport implements UserDao {@Overridepublic void save(User u) {String sql = "insert into user values('1',?) ";super.getJdbcTemplate().update(sql, u.getName());}@Overridepublic void delete(Integer id) {String sql = "delete from user where id = ? ";super.getJdbcTemplate().update(sql,id);}@Overridepublic void update(User u) {String sql = "update  user set name = ? where id=? ";super.getJdbcTemplate().update(sql, u.getName(),u.getId());}@Overridepublic User getById(Integer id) {String sql = "select * from user where id = ? ";return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u = new User();u.setId(rs.getInt("id"));u.setName(rs.getString("name"));return u;}}, id);}@Overridepublic int getTotalCount() {String sql = "select count(*) from user  ";Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);return count;}@Overridepublic List<User> getAll() {String sql = "select * from user  ";List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u = new User();u.setId(rs.getInt("id"));u.setName(rs.getString("name"));return u;}});return list;}
}

3、建立数据库链接配置文件

jdbc.jdbcUrl=jdbc:mysql:///spring
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=1234

4、在spring容器中进行配置

<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />
<!-- 将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" ><property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property><property name="driverClass" value="${jdbc.driverClass}" ></property><property name="user" value="${jdbc.user}" ></property><property name="password" value="${jdbc.password}" ></property>
</bean>
<!-- 将UserDao放入spring容器 -->
<bean name="userDao" class="com.jichi.jdbctemplate.UserDaoImpl" ><property name="dataSource" ref="dataSource" ></property>
</bean>

5、由于userDaoImpl已经继承了jdbcDaoSupport。jdbcDaoSupport中已经定义了jdbcTemplate,同时内置了setDataSource。可以自动将连接池放入。源码如下:

/** Copyright 2002-2012 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package org.springframework.jdbc.core.support;import java.sql.Connection;
import javax.sql.DataSource;import org.springframework.dao.support.DaoSupport;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.support.SQLExceptionTranslator;/*** Convenient super class for JDBC-based data access objects.** <p>Requires a {@link javax.sql.DataSource} to be set, providing a* {@link org.springframework.jdbc.core.JdbcTemplate} based on it to* subclasses through the {@link #getJdbcTemplate()} method.** <p>This base class is mainly intended for JdbcTemplate usage but can* also be used when working with a Connection directly or when using* {@code org.springframework.jdbc.object} operation objects.** @author Juergen Hoeller* @since 28.07.2003* @see #setDataSource* @see #getJdbcTemplate* @see org.springframework.jdbc.core.JdbcTemplate*/
public abstract class JdbcDaoSupport extends DaoSupport {private JdbcTemplate jdbcTemplate;/*** Set the JDBC DataSource to be used by this DAO.*/public final void setDataSource(DataSource dataSource) {if (this.jdbcTemplate == null || dataSource != this.jdbcTemplate.getDataSource()) {this.jdbcTemplate = createJdbcTemplate(dataSource);initTemplateConfig();}}/*** Create a JdbcTemplate for the given DataSource.* Only invoked if populating the DAO with a DataSource reference!* <p>Can be overridden in subclasses to provide a JdbcTemplate instance* with different configuration, or a custom JdbcTemplate subclass.* @param dataSource the JDBC DataSource to create a JdbcTemplate for* @return the new JdbcTemplate instance* @see #setDataSource*/protected JdbcTemplate createJdbcTemplate(DataSource dataSource) {return new JdbcTemplate(dataSource);}/*** Return the JDBC DataSource used by this DAO.*/public final DataSource getDataSource() {return (this.jdbcTemplate != null ? this.jdbcTemplate.getDataSource() : null);}/*** Set the JdbcTemplate for this DAO explicitly,* as an alternative to specifying a DataSource.*/public final void setJdbcTemplate(JdbcTemplate jdbcTemplate) {this.jdbcTemplate = jdbcTemplate;initTemplateConfig();}/*** Return the JdbcTemplate for this DAO,* pre-initialized with the DataSource or set explicitly.*/public final JdbcTemplate getJdbcTemplate() {return this.jdbcTemplate;}/*** Initialize the template-based configuration of this DAO.* Called after a new JdbcTemplate has been set, either directly* or through a DataSource.* <p>This implementation is empty. Subclasses may override this* to configure further objects based on the JdbcTemplate.* @see #getJdbcTemplate()*/protected void initTemplateConfig() {}@Overrideprotected void checkDaoConfig() {if (this.jdbcTemplate == null) {throw new IllegalArgumentException("'dataSource' or 'jdbcTemplate' is required");}}/*** Return the SQLExceptionTranslator of this DAO's JdbcTemplate,* for translating SQLExceptions in custom JDBC access code.* @see org.springframework.jdbc.core.JdbcTemplate#getExceptionTranslator()*/protected final SQLExceptionTranslator getExceptionTranslator() {return getJdbcTemplate().getExceptionTranslator();}/*** Get a JDBC Connection, either from the current transaction or a new one.* @return the JDBC Connection* @throws CannotGetJdbcConnectionException if the attempt to get a Connection failed* @see org.springframework.jdbc.datasource.DataSourceUtils#getConnection(javax.sql.DataSource)*/protected final Connection getConnection() throws CannotGetJdbcConnectionException {return DataSourceUtils.getConnection(getDataSource());}/*** Close the given JDBC Connection, created via this DAO's DataSource,* if it isn't bound to the thread.* @param con Connection to close* @see org.springframework.jdbc.datasource.DataSourceUtils#releaseConnection*/protected final void releaseConnection(Connection con) {DataSourceUtils.releaseConnection(con, getDataSource());}}

6、编写测试类

    @Testpublic void fun2() throws Exception{User u = new User();u.setName("tom");ud.save(u);}

7、执行成功

二、spring整合jdbctemplate

1、导入所需jar包。

除了之前介绍的spring的基础包,还需要导入数据库连接池包,jdbc驱动包,spring的jdbc包,spring的事务。

2、配置jdbctemplate

<!-- 指定spring读取db.properties配置 -->
<context:property-placeholder location="classpath:db.properties"  />
<!-- 1.将连接池放入spring容器 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" ><property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property><property name="driverClass" value="${jdbc.driverClass}" ></property><property name="user" value="${jdbc.user}" ></property><property name="password" value="${jdbc.password}" ></property>
</bean>
<!-- 2.将JDBCTemplate放入spring容器 -->
<bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" ><property name="dataSource" ref="dataSource" ></property>
</bean>
<!-- 3.将UserDao放入spring容器 -->
<bean name="userDao" class="com.jichi.jdbctemplate.UserDaoImpl" ><property name="jdbcTemplate" ref="jdbcTemplate" ></property>
</bean>

3、书写dao层代码

public class UserDaoImpl  implements UserDao {@Resourceprivate JdbcTemplate jdbcTemplate;@Overridepublic void save(User u) {String sql = "insert into user values('1',?) ";jdbcTemplate.update(sql, u.getName());}@Overridepublic void delete(Integer id) {String sql = "delete from user where id = ? ";jdbcTemplate.update(sql,id);}@Overridepublic void update(User u) {String sql = "update  user set name = ? where id=? ";jdbcTemplate.update(sql, u.getName(),u.getId());}@Overridepublic User getById(Integer id) {String sql = "select * from user where id = ? ";return jdbcTemplate.queryForObject(sql,new RowMapper<User>(){@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u = new User();u.setId(rs.getInt("id"));u.setName(rs.getString("name"));return u;}}, id);}@Overridepublic int getTotalCount() {String sql = "select count(*) from user  ";Integer count = jdbcTemplate.queryForObject(sql, Integer.class);return count;}@Overridepublic List<User> getAll() {String sql = "select * from user  ";List<User> list = jdbcTemplate.query(sql, new RowMapper<User>(){@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u = new User();u.setId(rs.getInt("id"));u.setName(rs.getString("name"));return u;}});return list;}
}

4、书写测试方法

    @Testpublic void fun2() throws Exception{User u = new User();u.setName("tom");ud.save(u);}

三、spring中jdbctemplate的相关方法

1、update

用来执行insert,update,delete语句。

    @Overridepublic void save(User u) {String sql = "insert into user values('1',?) ";jdbcTemplate.update(sql, u.getName());}@Overridepublic void delete(Integer id) {String sql = "delete from user where id = ? ";jdbcTemplate.update(sql,id);}@Overridepublic void update(User u) {String sql = "update  user set name = ? where id=? ";jdbcTemplate.update(sql, u.getName(),u.getId());}

2、查询某一具体类

    @Overridepublic int getTotalCount() {String sql = "select count(*) from user  ";Integer count = jdbcTemplate.queryForObject(sql, Integer.class);return count;}

3、将查询的数据封入实体类(单个对象,实现rowmapper接口)

    @Overridepublic User getById(Integer id) {String sql = "select * from user where id = ? ";return jdbcTemplate.queryForObject(sql,new RowMapper<User>(){@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u = new User();u.setId(rs.getInt("id"));u.setName(rs.getString("name"));return u;}}, id);}

4、将查询的数据封入实体类(list对象,实现rowmapper接口)

    @Overridepublic List<User> getAll() {String sql = "select * from user  ";List<User> list = jdbcTemplate.query(sql, new RowMapper<User>(){@Overridepublic User mapRow(ResultSet rs, int arg1) throws SQLException {User u = new User();u.setId(rs.getInt("id"));u.setName(rs.getString("name"));return u;}});return list;}

5、根据数据库查出的字段与实体类字段名自动对应

    @Overridepublic List<User> getAll() {String sql = "select * from user  ";List<User> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class));return list;}

Spring入门详细教程(四)相关推荐

  1. spring入门详细教程(五)

    前言 本篇紧接着spring入门详细教程(三),建议阅读本篇前,先阅读第一篇,第二篇以及第三篇.链接如下: Spring入门详细教程(一) https://www.cnblogs.com/jichi/ ...

  2. Spring入门详细教程(三)

    前言 本篇紧接着spring入门详细教程(二),建议阅读本篇前,先阅读第一篇和第二篇.链接如下: Spring入门详细教程(一) https://www.cnblogs.com/jichi/p/101 ...

  3. Spring入门详细教程(二)

    前言 本篇紧接着spring入门详细教程(一),建议阅读本篇前,先阅读第一篇.链接如下: Spring入门详细教程(一) https://www.cnblogs.com/jichi/p/1016553 ...

  4. Spring入门详细教程(一)

    一.spring概述 Spring是一个开放源代码的设计层面框架,他解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用.Spring是于2003 年兴起的一个轻量级的 ...

  5. MVC5+EF6 入门完整教程四

    MVC5+EF6 入门完整教程四 原文:MVC5+EF6 入门完整教程四 上篇文章主要讲了如何配置EF, 我们回顾下主要过程: 创建Data Model à 创建Database Context à创 ...

  6. ThinkJS框架入门详细教程(二)新手入门项目

    一.准备工作 参考前一篇:ThinkJS框架入门详细教程(一)开发环境 安装thinkJS命令 npm install -g think-cli 监测是否安装成功 thinkjs -v 二.创建项目 ...

  7. NMAP入门详细教程

    NAMP入门详细教程 一.功能: 网络扫描和嗅探. 二.原理: 使用TCP/IP协议栈指纹准确地判断目标主机的相关信息. 三.作用: 识别活跃主机 识别开放端口以及相关的服务 识别主机的系统指纹 路由 ...

  8. Pandas入门详细教程

    作者:luanhz 来源:小数志 导读 本文主要是对pandas进行入门详细介绍,通过本文你将系统性了解pandas为何会有数据分析界"瑞士军刀"的盛誉. 行文二级目录 01 关于 ...

  9. numpy入门详细教程(一)

    本讲主要介绍对numpy库和numpy库的N维数组对象:ndarray的基本了解.更多内容请看numpy入门详细教程(二) numpy: NumPy是一个开源的Python科学计算基础库,包含: • ...

最新文章

  1. Javascript到PHP加密通讯的简单实现
  2. python urllib的用法实例
  3. java dozer 深度_java – Dozer深度映射设置为Set
  4. 控件事件的绑定与取消
  5. 网页MSN,QQ,Skype,贸易通,雅虎通在线客服代码合集
  6. 使用#传递参数防御SQL注入攻击
  7. 【GDSOI2019】滑稽二乘法【数据结构】【LCT】
  8. ACL2021中的25个Transformers模型
  9. Bootstrap教程:[4]栅格系统详解
  10. oracle查看所有用户6,CSS_Oracle 用户权限查询,1.查看所有用户:nb - phpStudy
  11. 虚幻4引擎开发的手游_2019虚幻4手游大作排行-虚幻引擎开发的手机游戏
  12. 视觉SLAM十四讲 第7讲 (3) 相机运动估计 2D-2D/3D-2D/3D-3D
  13. PHP中的定界符 echo
  14. 荣耀20特别版 鸿蒙,【首发】鸿蒙OS华为首款特别版荣耀20全球发布,3999元你会支持吗...
  15. 杨氏模量(E)的处理方式对于封装翘曲的影响居然有这么大
  16. mysql缩写月名转换_mysql数据库时间、字符串类型互转
  17. 哈哈日语 五十音图之あ段音
  18. 学习一样新东西行而有效的方法
  19. Paper写作如何锻炼逻辑思维能力?
  20. php 直播流,ngnix开发(五)将rtmp直播流转换成hls直播流

热门文章

  1. mysql多数据源切换_Springboot项目实现Mysql多数据源切换的完整实例
  2. desk next the to_仁爱版七年级下册英语句型转换题型专练
  3. 文件管理服务器主机,通过BlueHost主机文件管理器上传文件
  4. php new redis错误,解决PHP Redis扩展无法加载的问题(zend_new_interned_string in Unknown on line 0)...
  5. 皮一皮:这真是兄弟能做的事???
  6. 皮一皮:流散国外的珍宝。。。
  7. 2021 年4月数据库流行度排行榜出炉!Snowflake 和 Clickhouse上升迅速!
  8. ThreadLocal 和神奇的数字 0x61c88647
  9. MySQL中只会count(),sum()?累加运算没听过?
  10. 计科系大一c语言期末考试题,大一大学计算机基础期末考试试题「附答案」