一、开发环境
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配置):
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/ispider_data
root
xxxxxx
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 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 findAllUser(){
String sql = "select * from myspringjdbcdb";
final List listAllUser = new ArrayList();
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 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 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 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