Spring JDBCTemplate配置使用
一、开发环境
Windows 10
IntelliJ IDEA 2016.1 旗舰版
JDK1.8
二、项目和数据库结构
项目结构:


数据库(MySQL 5.5.39):
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50539
Source Host : localhost:3306
Source Database : ispider_data
Target Server Type : MYSQL
Target Server Version : 50539
File Encoding : 65001
Date: 2016-04-11 10:11:09
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `myspringjdbcdb`
-- ----------------------------
DROP TABLE IF EXISTS `myspringjdbcdb`;
CREATE TABLE `myspringjdbcdb` (
`u_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`u_name` varchar(100) NOT NULL,
`u_password` varchar(200) NOT NULL,
PRIMARY KEY (`u_id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of myspringjdbcdb
-- ----------------------------
INSERT INTO `myspringjdbcdb` VALUES ('7', '张三', 'zhangsan');
INSERT INTO `myspringjdbcdb` VALUES ('8', '李四', 'lisi');
INSERT INTO `myspringjdbcdb` VALUES ('9', '王五', 'wangwu');

三、代码分析
1、配置上mysql的连接驱动
注意:需要引入jdbc jar包。
在applicationContext.xml中进行配置(包含了下文的bean配置):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref local="dataSource"/>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/ispider_data</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>xxxxxx</value>
</property>
</bean>
<bean id="userDAO" class="springjdbc.dao.impl.UserDaoImpl">
<property name="jdbcTemplate">
<ref bean="jdbcTemplate"/>
</property>
</bean>
<bean id="user" class="springjdbc.pojo.User">
<property name="dao">
<ref bean="userDAO"/>
</property>
</bean>
</beans>
2、UserDao.java
package springjdbc.dao;
import springjdbc.pojo.User;
import java.util.List;
/**
* Created by LTN on 2016/4/8.
*/
public interface UserDao {
List<User> findAllUser();
void create(String id, String name,String password);
void execInsert(String sql);
}
3、UserDaoImp.java
package springjdbc.dao.impl;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import springjdbc.dao.UserDao;
import springjdbc.pojo.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate;
public List<User> findAllUser(){
String sql = "select * from myspringjdbcdb";
final List<User> listAllUser = new ArrayList<User>();
jdbcTemplate.query(sql, new RowCallbackHandler() {
@Override
public void processRow(ResultSet resultSet) throws SQLException {
User u=new User();
u.setuName(resultSet.getString("u_name"));
u.setuPassword(resultSet.getString("u_password"));
u.setuId(resultSet.getString("u_id"));
listAllUser.add(u);
}
});
return listAllUser;
}
@Override
public void create(String id, String name,String password) {
String SQL = "insert into myspringjdbcdb (u_id, u_name, u_password) values (?, ?, ?)";
jdbcTemplate.update(SQL, id, name,password);
System.out.println("Created Record Id = " + id + " Name = " +name + "Password = " + password);
}
@Override
public void execInsert(String sql) {
jdbcTemplate.execute(sql);
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
}
注意在applicationContext.xml中配置userDAOI的 bean。
4、User.java
package springjdbc.pojo;
import springjdbc.dao.UserDao;
import java.util.List;
/**
* Created by LTN on 2016/4/8.
*/
public class User {
private String uId;
private String uName;
private String uPassword;
private UserDao dao;
public User() {
}
public void setDao(UserDao dao) {
this.dao = dao;
}
public UserDao getDao() {
return dao;
}
public String getuId() {
return uId;
}
public void setuId(String uId) {
this.uId = uId;
}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public String getuPassword() {
return uPassword;
}
public void setuPassword(String uPassword) {
this.uPassword = uPassword;
}
public User(String uName,String uPassword) {
this.uName=uName;
this.uPassword=uPassword;
}
public List<User> findAllUser(){
return dao.findAllUser();
}
public String toString(){
return "User [dao="+dao+", uId="+uId+", uName"+uName+", uPassword="+uPassword+"]";
}
}
注意在applicationContext.xml中配置user的bean。
5、编写测试类TestAction.java
package springjdbc.action;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import springjdbc.pojo.User;
import java.util.List;
/**
* Created by LTN on 2016/4/11.
*/
public class TestAction {
public static void main(String[] args) {
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
User user = (User) factory.getBean("user");
List<User> list=user.findAllUser();
System.out.println(list);
}
}
另一个测试类:
package springjdbc.action;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import scala.actors.threadpool.Arrays;
import springjdbc.dao.UserDao;
import springjdbc.dao.impl.UserDaoImpl;
import springjdbc.pojo.User;
import javax.sql.DataSource;
import java.util.List;
/**
* Created by LTN on 2016/4/11.
*/
public class MyTest {
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource ds) {
this.dataSource = ds;
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/conf/datasources.xml");
UserDao userDao=(UserDao)context.getBean("userDAO");
// userDao.create("003","java","psw");
String sql2="insert into myspringjdbcdb (u_id, u_name, u_password) values ('4','smith','pw007')";
userDao.execInsert(sql2);
List<User> list=userDao.findAllUser();
System.out.print(list.size());
}
}
代码完结。
四、运行后的结果
INFO - Loading XML bean definitions from class path resource [applicationContext.xml]
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/F:/workspace_idea/ISpider/WebContent/WEB-INF/lib/phoenix-4.2.2-client.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/F:/workspace_idea/ISpider/WebContent/WEB-INF/lib/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
INFO - Loaded JDBC driver: com.mysql.jdbc.Driver
[User [dao=null, uId=7, uName张三, uPassword=zhangsan], User [dao=null, uId=8, uName李四, uPassword=lisi], User [dao=null, uId=9, uName王五, uPassword=wangwu]]
Process finished with exit code 0
参考资料:
【1】Spring中的JDBCTemplate使用(非常详细的配置过程)
http://www.blogjava.net/hyljava/archive/2013/02/22/spring-jdbctemplate.html
【2】baidu: JdbcTemplae使用入门&&Spring三种连接池配置&&Spring配置文件引用外部properties文件
【3】Spring:JdbcTemplate使用指南
http://www.cnblogs.com/chenying99/archive/2012/08/06/2625936.html
【4】Spring源码学习-bean加载
http://www.blogjava.net/yangaiyou/archive/2014/08/29/417486.html
Spring JDBCTemplate配置使用的更多相关文章
- 【Spring】Spring的数据库开发 - 1、Spring JDBC的配置和Spring JdbcTemplate的解析
Spring JDBC 文章目录 Spring JDBC Spring JdbcTemplate的解析 Spring JDBC的配置 简单记录-Java EE企业级应用开发教程(Spring+Spri ...
- Spring jdbctemplate和事务管理器 全注解配置 不使用xml
/** * spring的配置类,相当于bean.xml */@Configuration//@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans ...
- Spring JdbcTemplate 的使用与学习(转)
紧接上一篇 (JdbcTemplate是线程安全的,因此可以配置一个简单的JdbcTemplate实例,将这个共享的实例注入到多个DAO类中.辅助的文档) Spring DAO支持 http://ww ...
- 使用Spring JDBCTemplate简化JDBC的操作
使用Spring JDBCTemplate简化JDBC的操作 接触过JAVA WEB开发的朋友肯定都知道Hibernate框架,虽然不否定它的强大之处,但个人对它一直无感,总感觉不够灵活,太过臃肿了. ...
- Apache Phoenix JDBC 驱动和Spring JDBCTemplate的集成
介绍:Phoenix查询引擎会将SQL查询转换为一个或多个HBase scan,并编排运行以生成标准的JDBC结果集. 直接使用HBase API.协同处理器与自己定义过滤器.对于简单查询来说,其性能 ...
- 基于注解的Spring事务配置
spring采用@Transactional注解进行事务申明,@Transactional既可以在方法上申明,也可以在类上申明,方法申明优先于类申明. 1.pom配置 包括spring核心包引入以及s ...
- Spring JdbcTemplate 查询结果集Map反向生成Java实体(转)
原文地址:Spring JdbcTemplate 查询结果集Map反向生成Java实体 以前写过一篇文章吐槽过Spring JdbcTemplate的queryForList方法(参见:http:// ...
- Spring JPA配置讲解
JPA是Java EE5规范之一,是一个orm规范,由厂商来实现该规范.目前有hibernate,OpenJPA,TopLink和EclipseJPA等实现 Spring提供三种方法集成JPA: 1. ...
- [转] Spring Boot配置多个DataSource
[From] https://www.liaoxuefeng.com/article/001484212576147b1f07dc0ab9147a1a97662a0bd270c20000 Sprin ...
随机推荐
- Technocup 2019 C. Compress String
一个字符串 $s$,你要把它分成若干段,有两种合法的段 1.段长为 $1$,代价为 $a$ 2.这个段是前面所有段拼起来组成的字符串的字串,代价为 $b$ 问最小代价 $|s| \leq 5000$ ...
- MySQL_截止昨日南京市所有在职业务员业绩排名-20170116
#计算南京销售员总业绩排名 数据结果已打乱处理 #职工信息表包含在职和离职两种状态 因此不能以这表当做主表 不然离职人的数据也会出现 以毛利表为主表 销售员限制在昨天在职的销售范围内 且和后面left ...
- 如何让 PADS Layout 识别到板框
如何让 PADS Layout 识别到板框 在很久很久以前 PADS Laout 还是 PowerPCB 的时候,铺铜是不认识板框的. 当有铺铜时必须复制一份板框再设置为铺铜才可以. 但到了 PADS ...
- (C#)Windows Shell 外壳编程系列2 - 解释,从“桌面”开始展开
(本系列文章由柠檬的(lc_mtt)原创,转载请注明出处,谢谢-) 接上一篇:(C#)Windows Shell 外壳编程系列1 - 基础,浏览一个文件夹 让我们详细解释一下 Shell 编程中最基本 ...
- (转载)Windows: "net use" command introduction
1)建立空连接: net use ""IP"ipc$ "" /user:"" (一定要注意:这一行命令中包含了3个空格) 2)建立 ...
- 单端IO标准
单端标准 常用的单端IO标准是LVTTL和LVCMOS. 目前业界绝大部分FPGA/CPLD器件的LVCOMS的IO是由CMOS推挽(push-pull)驱动器构成的,这种结构是上面的PMOS管和下面 ...
- NB-LOT 科普
最全科普!你一定要了解的NB-IoT 2017-06-19 21:04物联网/操作系统/科普 工信部下发通知推动150万NB-IoT基站落地.NB-IoT汹涌而来.很多网友要求雇佣军科普一篇NB-Io ...
- 获取APK的package名和activity名
使用 aapt dump badging + 需要安装的APK
- install命令和cp命令的区别
基本上,在Makefile里会用到install,其他地方会用cp命令. 它们完成同样的任务——拷贝文件,它们之间的区别主要如下: 1.最重要的一点,如果目标文件存在,cp会先清空文件后往里写入新文件 ...
- “百度杯”CTF比赛 十一月场(Misc)
签到题: 题目提示: 文件在i春秋的ctf2群里,加群下载文件 下载下来之后发现有压缩密码 题目提示有提示解压密码:key:ichunqiumemeda 打开文件,得到flag 签到题2: 点击下载附 ...