目录
JdbcTemplate概述
JdbcTemplate开发步骤
pom.xml中
测试java中实体类中
domain包下的account类下
运行结果:
Spring产生JdbcTemplate对象
测试插入
在applicationContext1.xml下
pom.xml中
JdbcTemplateTest类下
运行结果:
数据库中的变化
JdbcTemplate概述
他是spring框架中提供的一个对象,是对原始繁琐的jdbc API对象的简单封装。spring框架为我们提供了很多的操作模板类。例如:操作关系型数据的JdbcTemplate和HivernateTenplate,操作nosql数据库的RedisTemplate,操作消息队列的JmsTemplate等
JdbcTemplate开发步骤
- ①导入spring-jdbc和spring-tx坐标
- ②创建数据库表和实体
- ③创建JdbcTemplate对象
- ④执行数据库操作
数据库中account表
pom.xml中
org.springframework spring-jdbc5.0.5.RELEASE org.springframework spring-tx5.0.5.RELEASE
测试java中实体类中
package test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.jdbc.core.JdbcTemplate;
import java.beans.PropertyVetoException;
public class JdbcTemplateTest {
@Test
//测试JdbcTemplate开发步骤
public void test1() throws PropertyVetoException {
//创建数据源对象
ComboPooledDataSource dataSource=new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
//位置为本地,3306端口,test数据库
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
//用户名
dataSource.setUser("root");
//用户密码
dataSource.setPassword("123456");
JdbcTemplate jdbcTemplate=new JdbcTemplate();
//设置数据源对象,知道数据库在哪里
jdbcTemplate.setDataSource(dataSource);
//执行操作
int row = jdbcTemplate.update("insert into account value(?,?)", "tom", 5000);
System.out.println(row);
}
}
domain包下的account类下
package domain;
public class Account {
private String name;
private double money;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"name='" + name + ''' +
", money=" + money +
'}';
}
}
运行结果:
数据库中的test数据库,account表
Spring产生JdbcTemplate对象
测试插入
仔细看,这些都是参数注入(用了setXxx。。),我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将数据源DateSource注入到JdbcTemplate模版对象中,配置如下:
在test测试包下创建一系列
在applicationContext1.xml下
pom.xml中
4.0.0 org.example javaMaven021.0-SNAPSHOT mysql mysql-connector-java5.1.32 c3p0 c3p00.9.1.2 com.alibaba druid1.1.10 junit junit4.11 org.springframework spring-test5.0.5.RELEASE org.springframework spring-context5.0.5.RELEASE compile org.springframework spring-web5.0.5.RELEASE org.springframework spring-webmvc5.0.5.RELEASE com.fasterxml.jackson.core jackson-core2.9.0 com.fasterxml.jackson.core jackson-databind2.9.0 com.fasterxml.jackson.core jackson-annotations2.9.0 org.springframework spring-jdbc5.0.5.RELEASE org.springframework spring-tx5.0.5.RELEASE
JdbcTemplateTest类下
public class JdbcTemplateTest {
@Test
//测试Spring产生jdbcTemplate对象
public void test2() throws PropertyVetoException {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext1.xml");
JdbcTemplate jdbcTemplate=app.getBean(JdbcTemplate.class);
int row = jdbcTemplate.update("insert into account value(?,?)", "KC", 50000);
System.out.println(row);
}
}
运行结果:
数据库中的变化



