Spring 开发第一步(三)Spring与JDBC
《spring in action 3rd》中的前面4章讲解的是Spring的核心,也就是DI/IOC和AOP 。从第5章开始是Spring在企业开发中的各个方面的应用。其实作为笔者从事的企业计算来说,J2EE相关的最常见的内容就是如何持久化了,第5、6章讲的就是这方面的内容。
今天主要学习了Spring与JDBC开发。
一、配置数据源
首先我们需要配置数据源,在设置好context.xml后,我们将JDBC数据源配置到Spring:
<jee:jndi-lookup id="dataSource" jndi-name="/jdbc/spitter" resource-ref="true" /> 对,就这么一句话。并且id为dataSource的这个数据源可以像一个bean那样注入到另一个bean里。
比如注入到下面的DSTestBean
package com.spitter.test;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
public class DSTestBean {
@Autowired
private DataSource dataSource;
public void setDataSource(DataSource dataSource){
this.dataSource = dataSource;
}
public DataSource getDataSource(){
return this.dataSource;
}
}
对应的spring配置文件如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<!-- Beans declarariona go here -->
<context:annotation-config/>
<jee:jndi-lookup id="dataSource" jndi-name="/jdbc/spitter" resource-ref="true" />
<bean id="dsTest" class="com.spitter.test.DSTestBean" />
</beans>
注意,由于在DSTestBean中我们对dataSource属性使用了注解注入 @autowired
所以在配置文件里要加入<context:annotation-config/> ,因为Spring 默认是关闭注解装配方式的。
二、使用Spring的template简化JDBC代码
假设有如下简单的表结构

使用原生的JDBC开发一个根据city_code查询city_name的方法,一般有如下代码
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = ds.getConnection();
pstmt = conn.prepareStatement("select city_name from ta_ds_test where city_code='hz'");
rs = pstmt.executeQuery();
while(rs.next()){
//System.out.println("city_name = "+ rs.getString(1));
cityName = rs.getString(1);
}
} catch (SQLException e) { }finally{
if(rs!=null)
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(pstmt!=null)
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(conn!=null)
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
而使用SimpleJdbcTemplate简化后
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<bean id="jdbcTemplateDao" class="com.spitter.test.JdbcTemplateDao" />
@SuppressWarnings("deprecation")
@Autowired
private SimpleJdbcTemplate jdbcTemplate;public String getCityNameByCode(String cityCode){
return this.jdbcTemplate.queryForObject("select city_name from ta_ds_test where city_code=?", String.class, cityCode);
}
高下立判!
上面的代码仍有一个问题:显然我们需要将配置文件中的jdbcTemplate对象注入到每一个需要使用它的dao中,尽管我们在jdbcTemplateDao使用了@Autowired注解来简化代替在配置文件中注入,但是这也需要在每个dao里添加注解啊。
所以,最佳实践是,让每个dao去继承SimpleJdbcDaoSupport
<bean id="jdbcTemplateDao" class="com.spitter.test.JdbcTemplateDao" p:dataSource-ref="dataSource"/>
public String getCityNameByCode(String cityCode){
return getSimpleJdbcTemplate().queryForObject("select city_name from ta_ds_test where city_code=?", String.class, cityCode);
}
这也就不需要在配置文件中去配jdbcTemplate了,当然也不需要去dao里添加注解了。数据源原本是 dataSource -> template ->dao 这样一个注入顺序,现在我们将数据源直接注入dao从SimpleJdbcDaoSupport继承而来的dataSource属性中去( 如上所示 p:dataSource-ref="dataSource" ) 。
Spring 开发第一步(三)Spring与JDBC的更多相关文章
- Spring 开发第一步(四)Spring与JDBC事务
Spring使用各种不同的TransactionManager来管理各种不同数据源事务底层(比如jdbc数据源.hibernate数据源.JPA数据源等等).在此基础上使用各种对应的Template来 ...
- Spring 开发第一步
经过今天上午的学习发现spring上手开发一个"hello world"真的非常简单. 开发环境搭建: 1.去spring官网下载spring-framework-3.2.11.R ...
- Spring 开发第一步(二)
今天继续学习<Spring in action 3rd>并运行书中的例子,到了第4章aop,是加入一个作为切面的Audience类,将Performer的perform()方法作为切点来进 ...
- Spring Boot 项目学习 (三) Spring Boot + Redis 搭建
0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...
- 我的自定义框架 || 基于Spring Boot || 第一步
今天在园子里面看到一位大神写的springboot做的框架,感觉挺不错,遂想起来自己还没有一个属于自己的框架,决定先将大神做好的拿过来,然后加入自己觉得需要的模块,不断完善 目前直接复制粘贴过来的,后 ...
- Spring入门第一课:Spring基础与配置Bean
1.入门 Spring是简化java开发的一个框架,其中IoC和AOP是Spring的两个重要核心.由于Spring是非侵入性的,通过Ioc容器来管理bean的生命周期,还整合了许多其他的优秀框架,所 ...
- 一起来学spring Cloud | 第一章:spring Cloud 与Spring Boot
目前大家都在说微服务,其实微服务不是一个名字,是一个架构的概念,大家现在使用的基于RPC框架(dubbo.thrift等)架构其实也能算作一种微服务架构. 目前越来越多的公司开始使用微服务架构,所以在 ...
- Andriod开发第一步-部署环境(搬运&&总结)
第一步:安装JDK 第二步:配置Windows上JDK的变量环境 第三步:下载安装Eclipse 第四步:下载安装Android SDK 配置了JDK变量环境, ...
- Spring框架第一篇之Spring的第一个程序
一.下载Spring的jar包 通过http://repo.spring.io/release/org/springframework/spring/地址下载最新的Spring的zip包,当然,如果你 ...
随机推荐
- CentOS下zabbix监控mysql5.6版本主从
目录 CentOS下zabbix监控mysql5.6版本主从 1. Zabbix添加自定义监控流程 2. 具体步骤 1. 编写监控mysql主从脚本 2. mysql赋权 3. 查看脚本执行效果 4. ...
- 类实现Parcelable接口在Intent中传递
类实现了Parcelable接口就可以在Intent中传递 只要在类的定义中实现Parcelable接口 代码 package entity; import android.os.Parcel; ...
- Tomcat:A cookie header was received[xxxxxx] that contained an invalid cookie. That cookie will be ignored.
搬运来源:https://blogs.yahoo.co.jp/dk521123/36721868.html 原因: *从Tomcat 8,Cookie的解析已经符合RFC 6265. *由于RFC 6 ...
- PAT 1054 求平均值 (20)(代码+思路+测试用例)
1054 求平均值 (20)(20 分) 本题的基本要求非常简单:给定N个实数,计算它们的平均值.但复杂的是有些输入数据可能是非法的.一个"合法"的输入是[-1000,1000]区 ...
- lib文件反汇编
运行vc命令行,输入:dumpbin /disasm xxx.lib > test.txt lib就是obj文件打包起来的,可以用lib.exe解出来,下面是vc环境下的操作,其他环境,看命令行 ...
- <Linux多线程服务端编程>学习记录
使用智能指针解决多线程下 类的解析冲突问题 有这样一个场景 使用StockFactory记录Stock的信息 容器是map<string,smart_ptr>; 代码如下: #inclu ...
- cocos2d-js 安卓自定义本地通知功能
安卓新手,笔记有理解不当的地方望指出,经过几天折腾终于可以实现类似ios的本地通知功能(ios就几行代码),可能有第三方sdk可以方便实现,暂时没去找 思路: 1. startService 和bin ...
- R 语言安装问题集锦
R安装问题R CMD INSTALL -l /data1/jhh/envirment/R/R_lib /data1/jhh/software/qvalue_2.10.0.tar.gz 问题1 :con ...
- Android 编译参数 LOCAL_MODULE_TAGS
此参数会影响到库生成后的存放位置,影响生成位置的应该是相关平台下的变量PRODUCT_PACKAGES http://blog.csdn.net/evilcode/article/details/64 ...
- PythonWEB框架之Flask--2
10.请求扩展 1 before_request 类比django中间件中的process_request,在青丘收到之前绑定一个函数做一些事情 #基于它做用户登录认证 @app.before_req ...