Spring入门详细教程(四)
前言
本篇紧接着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 {
@Override
public void save(User u) {
String sql = "insert into user values('1',?) ";
super.getJdbcTemplate().update(sql, u.getName());
}
@Override
public void delete(Integer id) {
String sql = "delete from user where id = ? ";
super.getJdbcTemplate().update(sql,id);
}
@Override
public void update(User u) {
String sql = "update user set name = ? where id=? ";
super.getJdbcTemplate().update(sql, u.getName(),u.getId());
}
@Override
public User getById(Integer id) {
String sql = "select * from user where id = ? ";
return super.getJdbcTemplate().queryForObject(sql,new RowMapper<User>(){
@Override
public 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);
}
@Override
public int getTotalCount() {
String sql = "select count(*) from user ";
Integer count = super.getJdbcTemplate().queryForObject(sql, Integer.class);
return count;
}
@Override
public List<User> getAll() {
String sql = "select * from user ";
List<User> list = super.getJdbcTemplate().query(sql, new RowMapper<User>(){
@Override
public 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() {
} @Override
protected 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、编写测试类
@Test
public 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 {
@Resource
private JdbcTemplate jdbcTemplate;
@Override
public void save(User u) {
String sql = "insert into user values('1',?) ";
jdbcTemplate.update(sql, u.getName());
}
@Override
public void delete(Integer id) {
String sql = "delete from user where id = ? ";
jdbcTemplate.update(sql,id);
}
@Override
public void update(User u) {
String sql = "update user set name = ? where id=? ";
jdbcTemplate.update(sql, u.getName(),u.getId());
}
@Override
public User getById(Integer id) {
String sql = "select * from user where id = ? ";
return jdbcTemplate.queryForObject(sql,new RowMapper<User>(){
@Override
public 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);
}
@Override
public int getTotalCount() {
String sql = "select count(*) from user ";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
@Override
public List<User> getAll() {
String sql = "select * from user ";
List<User> list = jdbcTemplate.query(sql, new RowMapper<User>(){
@Override
public 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、书写测试方法
@Test
public void fun2() throws Exception{
User u = new User();
u.setName("tom");
ud.save(u);
}
三、spring中jdbctemplate的相关方法
1、update
用来执行insert,update,delete语句。
@Override
public void save(User u) {
String sql = "insert into user values('1',?) ";
jdbcTemplate.update(sql, u.getName());
}
@Override
public void delete(Integer id) {
String sql = "delete from user where id = ? ";
jdbcTemplate.update(sql,id);
}
@Override
public void update(User u) {
String sql = "update user set name = ? where id=? ";
jdbcTemplate.update(sql, u.getName(),u.getId());
}
2、查询某一具体类
@Override
public int getTotalCount() {
String sql = "select count(*) from user ";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
return count;
}
3、将查询的数据封入实体类(单个对象,实现rowmapper接口)
@Override
public User getById(Integer id) {
String sql = "select * from user where id = ? ";
return jdbcTemplate.queryForObject(sql,new RowMapper<User>(){
@Override
public 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接口)
@Override
public List<User> getAll() {
String sql = "select * from user ";
List<User> list = jdbcTemplate.query(sql, new RowMapper<User>(){
@Override
public 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、根据数据库查出的字段与实体类字段名自动对应
@Override
public List<User> getAll() {
String sql = "select * from user ";
List<User> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(User.class));
return list;
}
Spring入门详细教程(四)的更多相关文章
- spring入门详细教程(五)
前言 本篇紧接着spring入门详细教程(三),建议阅读本篇前,先阅读第一篇,第二篇以及第三篇.链接如下: Spring入门详细教程(一) https://www.cnblogs.com/jichi/ ...
- Spring入门详细教程(三)
前言 本篇紧接着spring入门详细教程(二),建议阅读本篇前,先阅读第一篇和第二篇.链接如下: Spring入门详细教程(一) https://www.cnblogs.com/jichi/p/101 ...
- Spring入门详细教程(二)
前言 本篇紧接着spring入门详细教程(一),建议阅读本篇前,先阅读第一篇.链接如下: Spring入门详细教程(一) https://www.cnblogs.com/jichi/p/1016553 ...
- Spring入门详细教程(一)
一.spring概述 Spring是一个开放源代码的设计层面框架,他解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用.Spring是于2003 年兴起的一个轻量级的 ...
- ThinkJS框架入门详细教程(二)新手入门项目
一.准备工作 参考前一篇:ThinkJS框架入门详细教程(一)开发环境 安装thinkJS命令 npm install -g think-cli 监测是否安装成功 thinkjs -v 二.创建项目 ...
- RMAN详细教程(四):备份脚本实战操作
RMAN详细教程(一):基本命令代码 RMAN详细教程(二):备份.检查.维护.恢复 RMAN详细教程(三):备份脚本的组件和注释 RMAN详细教程(四):备份脚本实战操作 1.为了安全起见,先将数据 ...
- 经典Spring入门基础教程详解
经典Spring入门基础教程详解 https://pan.baidu.com/s/1c016cI#list/path=%2Fsharelink2319398594-201713320584085%2F ...
- Xcode和github入门详细教程
Xcode和github详细教程! 主要是参考了现在网上的一些资料给没整过的人一个详细的指南. (1)先在github上注册账号,自行解决! (2)在导航栏右上角new一个repository(仓库) ...
- SpringMVC框架详细教程(四)_使用maven导入各个版本的Spring依赖包
使用maven导入Spring依赖包 上一节讲了如何向动态Web项目添加下载的Spring依赖包,作为补充下面列出了如何使用 maven 导入Spring的依赖包,可以选择需要的导入(推荐)或者全部导 ...
随机推荐
- 【原创】sizeof运算符总结
sizeof运算符返回一条表达式或一个类型名字的所占字节数,返回值为size_t的常量表达式,注意:sizeof右结合,且为编译时计算,而非运行时 两种形式:sizeof (type)和sizeof ...
- 【原创】Git删除暂存区或版本库中的文件
0 基础 我们知道Git有三大区(工作区.暂存区.版本库)以及几个状态(untracked.unstaged.uncommited),下面只是简述下Git的大概工作流程,详细的可以参见本博客的 ...
- tomcat没有编译重新编写的代码
今天在工作的时候,我把项目的mapper.xml的的sql语句改了,但是在启动项目,在页面访问数据的时候,发现控制打印出来的sql语句还是原来的,没有改过来. 在tomcat里找到我的代码,找到我修改 ...
- jquery的jsonp的使用
客户端 $(function(){ $.ajax({ type: "get", async: false, url: "http://test.com/json_data ...
- python等值和大小比较
等值.大小比较 在python中,只要两个对象的类型相同,且它们是内置类型(字典除外),那么这两个对象就能进行比较.关键词:内置类型.同类型.所以,两个对象如果类型不同,就没法比较,比如数值类型的数值 ...
- Django 系列博客(二)
Django 系列博客(二) 前言 今天博客的内容为使用 Django 完成第一个 Django 页面,并进行一些简单页面的搭建和转跳. 命令行搭建 Django 项目 创建纯净虚拟环境 在上一篇博客 ...
- Spark内存管理机制
Spark内存管理机制 Spark 作为一个基于内存的分布式计算引擎,其内存管理模块在整个系统中扮演着非常重要的角色.理解 Spark 内存管理的基本原理,有助于更好地开发 Spark 应用程序和进行 ...
- Runtime详解(上)
这篇关于Runtime讲解参考https://juejin.im/post/593f77085c497d006ba389f0以及https://www.jianshu.com/p/6ebda3cd80 ...
- NLP入门(五)用深度学习实现命名实体识别(NER)
前言 在文章:NLP入门(四)命名实体识别(NER)中,笔者介绍了两个实现命名实体识别的工具--NLTK和Stanford NLP.在本文中,我们将会学习到如何使用深度学习工具来自己一步步地实现N ...
- 最全的.NET Core跨平台微服务学习资源没有之一
一.Asp.net Core基础 微软英文官网:https://docs.microsoft.com/en-us/aspnet/core/?view=aspnetcore-2.1 .NET Core: ...