JdbcTemplate概述
- 它是spring框架中提供的一个对象,是对原始Jdbc API对象的简单封装。
JdbcTemplate对象的创建
public JdbcTemplate() { }
public JdbcTemplate(DataSource dataSource) { setDataSource(dataSource);
afterPropertiesSet(); }
public JdbcTemplate(DataSource dataSource, boolean lazyInit) { setDataSource(dataSource);
setLazyInit(lazyInit); afterPropertiesSet(); }
除了默认构造函数之外,都需要提供一个数据源,可以依据依赖注入,在配置文件中配置这些对象。
Spring中配置数据源
环境搭建
编写spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
</beans>
配置数据源
- 可以使用C3P0、DBCP、spring内置三种数据源。
配置C3P0数据源
导入jar包,在spring的配置文件中配置:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql:///spring_day02"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
配置DBCP数据源
导入jar包,在spring的配置文件中配置
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> ‘
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:// /spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
配置spring内置数据库
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
或者
<context:property-placeholder location="classpath:jdbc.properties"/>
JdbcTemplate的CRUD操作
前期准备
创建数据库:
create database spring_day02;
use spring_day02;
创建表:
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
在spring配置文件中配置JdbcTemplate
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
<!-- 配置一个数据库的操作模板:JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///spring_day02"></property>
<property name="username" value="root"></property>
<property name="password" value="1234"></property>
</bean>
</beans>
基本使用
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
jt.execute("insert into account(name,money)values('eee',500)"); } }
保存操作
public class JdbcTemplateDemo3 { public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作
//保存
jt.update("insert into account(name,money)values(?,?)","fff",5000); } }
更新操作
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作 //修改
jt.update("update account set money = money-? where id = ?",300,6);
} }
删除操作
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作 //删除
jt.update("delete from account where id = ?",6); } }
查询所有操作
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作 //查询所有
List<Account> accounts = jt.query("select * from account where money > ? ", new AccountRowMapper(), 500);
for(Account o : accounts)
{
System.out.println(o); }
} }
public class AccountRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getFloat("money"));
return account; }
查询一个操作
使用 RowMapper 的方式:常用的方式
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作 //查询一个
List<Account> as = jt.query("select * from account where id = ? ",new AccountRowMapper(), 55);
System.out.println(as.isEmpty()?"没有结果":as.get(0)); }
}
使用 ResultSetExtractor 的方式:不常用的方式
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作 //查询一个
Account account = jt.query("select * from account where id = ?", new AccountResultSetExtractor(),3);
System.out.println(account); } }
查询返回一行一列操作
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取 Spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 id 获取 bean 对象
JdbcTemplate jt = (JdbcTemplate) ac.getBean("jdbcTemplate");
//3.执行操作 //查询返回一行一列:使用聚合函数,在不使用 group by 字句时,都是返回一行一列。最常用的就是分页中获取总记录条数
Integer total = jt.queryForObject("select count(*) from account where money > ? ",Integer.class,500);
System.out.println(total); }
}
在Dao中使用JdbcTemplate
准备实体类
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id; }
public void setId(Integer id) {
this.id = id; }
public String getName() {
return name; }
public void setName(String name) {
this.name = name; }
public Float getMoney() {
return money; }
public void setMoney(Float money) {
this.money = money; }
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", money=" + money + "]";}
}
第一种方式:在dao中定义JdbcTemplate
public interface IAccountDao { /**
* 根据 id 查询账户信息 * @param id * @return */
Account findAccountById(Integer id);
/**
* 根据名称查询账户信息 * @return */
Account findAccountByName(String name);
/**
* 更新账户信息 * @param account */
void updateAccount(Account account); }
/**
* 账户的持久层实现类 * 此版本的 dao,需要给 dao注入 JdbcTemplate */
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate; }
@Override
public Account findAccountById(Integer id) {
List<Account> list = jdbcTemplate.query("select * from account where id = ? ",new AccountRowMapper(),id);
return list.isEmpty()?null:list.get(0); }
@Override
public Account findAccountByName(String name) {
List<Account> list = jdbcTemplate.query("select * from account where name = ? ",new AccountRowMapper(),name);
if(list.isEmpty()){
return null; }
if(list.size()>1){
throw new RuntimeException("结果集不唯一,不是只有一个账户对象"); }
return list.get(0); }
@Override
public void updateAccount(Account account) {
jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId()); }
}