JdbcTemplate的作用:
为了使 JDBC 更加易于使用,Spring 在 JDBCAPI 上定义了一个抽象层, 以此建立一个JDBC存取框架.
作为 SpringJDBC 框架的核心, JDBC 模板的设计目的是为不同类型的JDBC操作提供模板方法. 每个模板方法都能控制整个过程,并允许覆盖过程中的特定任务.通过这种方式,可以在尽可能保留灵活性的情况下,将数据库存取的工作量降到最低.
JdbcTemplate主要提供以下五类方法:
execute | 可以用于执行任何SQL语句,一般用于执行DDL语句 |
---|---|
update | 用于执行新增、修改、删除等语句 |
batchUpdate | 执行批处理相关语句 |
query及queryForXXX | 执行查询相关语句 |
call | 执行存储过程、函数相关语句 |
spring对JDBC的封装使用步骤大体如下:
-导入jar包 spring-jdbc、spring-tx
-创建DriveManagerDataSource对象,对数据库进行配置
-创建JdbcTemplate对象
-注入dataSource对象
-调用JdbcTemplate封装的方法进行sql操作
利用spring的jdbcTemplate实现简单的sql操作实例:
首先在数据库新建一张表
CREATE TABLE `account` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(40) default NULL,
`money` float default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
INSERT INTO `account` VALUES ('1', 'aaa', '1000');
INSERT INTO `account` VALUES ('2', 'bbb', '1000');
在pom.xml文件中,增加依赖(坐标)
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
</dependencies>
编写账号实体类
/**
* 账户的实体类
* **/
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 +
'}';
}
}
JdbcTemplate的最基本用法(不使用Ioc)
/**
* JdbcTemplate的最基本用法
* **/
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
//准备数据源:spring的内置数据源
DriverManagerDataSource ds=new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/eesy");
ds.setUsername("root");
ds.setPassword("123");
//1.创建JdbcTemplate对象
JdbcTemplate jt=new JdbcTemplate(); //JdbcTemplate jt=new JdbcTemplate(ds);
//给jt设置数据源
jt.setDataSource(ds);
//2.执行操作
jt.execute("insert into account(name,money)values('ddd',1000)");
}
}
上述代码显然不是我们希望看到的,下面使用Spring的Ioc
JdbcTemplate在Spring的Ioc中使用
编写XML配置文件
<?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
https://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://localhost:3306/eesy"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
</beans>
JdbcTemplate用法
public class JdbcTemplateDemo1 {
public static void main(String[] args) {
//准备数据源:spring的内置数据源
DriverManagerDataSource ds=new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/eesy");
ds.setUsername("root");
ds.setPassword("123");
//1.创建JdbcTemplate对象
JdbcTemplate jt=new JdbcTemplate(); //JdbcTemplate jt=new JdbcTemplate(ds);
//给jt设置数据源
jt.setDataSource(ds);
//2.执行操作
jt.execute("insert into account(name,money)values('ddd',1000)");
}
}
---------------------------------------------------------------------------------------------------------------------
//使用XML配置如下面这种写法
public class JdbcTemplateDemo2 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jt=ac.getBean("jdbcTemplate",JdbcTemplate.class);
//3.执行操作
jt.execute("insert into account(name,money)values('eee',222)");
}
}
JdbcTemplate的CRUD
/**
* JdbcTemplate的CRUD操作
* **/
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jt=ac.getBean("jdbcTemplate",JdbcTemplate.class);
//3.执行操作
//保存
// jt.update("insert into account(name,money)values(?,?)","fff",111);
//更新
//jt.update("update account set name=?,money=? where id=?","aimaogoudexiaohao",628,4);
//删除
// jt.update("delete from account where id=?",3);
//查询所有
/* List<Account> accounts=jt.query("select * from account where money>?",new BeanPropertyRowMapper<Account>(Account.class),500);
for(Account account :accounts){
System.out.println(account);
}*/
//查询一个
/*List<Account> accounts=jt.query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),1);
System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));*/
//查询返回一行(使用聚合函数,但不加group by子句)
/*Long ll=jt.queryForObject("select count(*) from account where money>?",Long.class,500);
System.out.println(ll);*/
}
}
注意:List accounts=jt.query(“select * from account where money>?”,new BeanPropertyRowMapper(Account.class),500)其中的BeanPropertyRowMapper是Spring为我们提供的。下面 编写一个类来模拟一下原理。
模拟类
/**
* 定义Account的封装策略
* **/
class AccountRowMapper implements RowMapper<Account>{
/**
* 把结果集的数据封装到Account中,然后由spring把每个Account加到集合中
* **/
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account=new Account();
account.setId(resultSet.getInt("id"));
account.setName(resultSet.getString("name"));
account.setMoney(resultSet.getFloat("money"));
return account;
}
}
将JdbcTemplateDemo3类进行如下修改
public class JdbcTemplateDemo3 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
JdbcTemplate jt=ac.getBean("jdbcTemplate",JdbcTemplate.class);
//3.执行操作
//保存
// jt.update("insert into account(name,money)values(?,?)","fff",111);
//更新
//jt.update("update account set name=?,money=? where id=?","aimaogoudexiaohao",628,4);
//删除
// jt.update("delete from account where id=?",3);
//查询所有
/*List<Account> accounts=jt.query("select * from account where money>?",new AccountRowMapper(),500);
for(Account account :accounts){
System.out.println(account);
}*/
//查询一个
/*List<Account> accounts=jt.query("select * from account where id=?",new AccountRowMapper(),1);
System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));*/
//查询返回一行(使用聚合函数,但不加group by子句)
/*Long ll=jt.queryForObject("select count(*) from account where money>?",Long.class,500);
System.out.println(ll);*/
}
}
JdbcTemplate在Dao中的使用
编写账号的持久层接口
/**
* 账号的持久层接口
* **/
public interface IAccountDao {
/**
* 根据ID查询账户
* **/
Account findAccountById(Integer accountId);
/**
* 根据名字查询账户
* **/
Account findAccountByName(String accountName);
/**
* 更新账户
* **/
void updateAccount(Account account);
}
编写账户持久层实现类
/**
* 账户的持久层实现类
* **/
public class AccountDaoImpl implements IAccountDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public Account findAccountById(Integer accountId) {
List<Account>accounts=jdbcTemplate.query("select * from account where id=?",new BeanPropertyRowMapper<Account>(Account.class),2);
return accounts.isEmpty()?null:accounts.get(0);
}
public Account findAccountByName(String accountName) {
List<Account> accounts=jdbcTemplate.query("select * from account where name=?",new BeanPropertyRowMapper<Account>(Account.class),"aaa");
if(accounts.isEmpty()) {
return null;
}
if(accounts.size()>1){
throw new RuntimeException("结果集不唯一");
}
return accounts.get(0);
}
public void updateAccount(Account account) {
jdbcTemplate.update("updare account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}
}
修改XML配置文件,追加如下配置
<!--配置账户的持久层-->
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
编写测试类进行测试
/**
* JdbcTemplate的最基本用法
* **/
public class JdbcTemplateDemo4 {
public static void main(String[] args) {
//1.获取容器
ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml");
//2.获取对象
IAccountDao accountDao=ac.getBean("accountDao",IAccountDao.class);
Account account=accountDao.findAccountById(1);
System.out.println(account);
account.setMoney(10000f);
accountDao.updateAccount(account);
}
}
总结:JdbcTemplate是Spring框架自带的对JDBC操作的封装,目的是提供统一的模板方法使对数据库的操作更加方便、友好,效率也不错。但是功能还是不够强大(比如不支持级联属性),在实际应用中还需要和hibernate、mybaties等框架混合使用。
注:笔者学习Spring随笔笔记,水平有限,欢迎指出问题。