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包,当然,如果你 ...
随机推荐
- swift - 封装 GCDTimer 和 NSTimer
封装的类代码 import UIKit /// 控制定时器的类 class ZDTimerTool: NSObject { /// 定时器 // private var timer: Timer? / ...
- php 函数中静态变量的问题
<?php function msg() { static $a = 0; echo $a++, '<br />'; } msg(); msg(); msg(); 上述代码,分别输出 ...
- ubuntu自动拉黑破解ssh服务的IP
2013年的脚本,今天拿出来备份一下. vim /root/secure_ssh.sh #!/bin/bash cat /var/log/auth.log|awk '/Failed/{print $( ...
- python创建独立虚拟工作环境方法
前言: python的组件非常之多,有时这个项目依赖m个组件,有时那个项目依赖n个组件,时间一长很容易导致系统python环境的臃肿不堪,由此便有了virtualenv.virtualenvwrapp ...
- laravel的函数asset()、url()
1.asset():用于引入静态文件,如 css/JavaScript/images,文件必须存放在public文件目录下 src="{{ asset('home') }}/images/t ...
- Java数据结构和算法(一)线性结构
Java数据结构和算法(一)线性结构 数据结构与算法目录(https://www.cnblogs.com/binarylei/p/10115867.html) 线性表 是一种逻辑结构,相同数据类型的 ...
- Linux多线程服务端编程 使用muduo C++网络库 学习笔记 日志log
代码来自陈硕开源代码库 muduo中 地址是https://github.com/chenshuo/muduo #pragma once #include <string> #define ...
- $.post 提示错误: Uncaught SyntaxError: Unexpected token :
$.post("addRecommond",{"productId":productId,"categoryCode":categoryCo ...
- jquery 元素筛选 13.6.20
<ul> <li>list item 1</li> <li>list item 2</li> <li class="thir ...
- C变参数函数demo
#include <stdio.h> #include <stdarg.h> int sum(int a,...) { int temp = 0,sum=0,count ...