SpringのJdbcTemplate(四)

一、JdbcTemplate概要

1.1、JdbcTemplate简介

  JdbcTemplate的本质是一个对数据库操作的工具,和apache的DButil一样,都是对数据库进行更方便的操作。JdbcTemplate是Spring框架在jdbc上面做了一定的封装,使用spring的注入功能,将DataSource注册到JdbcTemplate之中。

优点
1、将jdbc创意创建连接、语句对象、设置SQL参数,释放资源等一系列操作封装到JdbcTemplate工具中,简化了代码量,使用方便简单。
2、运行期:高效、内嵌Spring框架中、支持基于AOP的声明式事务

缺点:必须于Spring框架结合在一起使用、不支持数据库跨平台、默认没有缓存


1.2、JdbcTemplate提供的方法

  JdbcTemplate位于中spring-jdbc-x.x.x .RELEASE.jar中。其全限定命名为org.springframework.jdbc.core.JdbcTemplate。要使用JdbcTemlate还需一个spring-tx-x.x.x, RELEASE.jar这个包包含了一下事务和异常控制。

(1)execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
(2)update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
(3)query方法及queryForXXX方法:用于执行查询相关语句;
(4)call方法:用于执行存储过程、函数相关语句。


1.3、Spring配置数据源的三种方式

方式一Spring内置数据源配置
Class:DriverManagerDataSource
全限定名:org.springframework.jdbc.datasource.DriverManagerDataSource
不需要添加任何jar


方式二apache的 dbcp数据源配置
Class:BasicDataSource
全限定名:org.apache.commons.dbcp.BasicDataSource
需要添加:com.springsource.org.apache.commons.dbcp-1.2.2.osgi.jar
com.springsource.org.apache.commons.pool-1.5.3.jar

方式三c3p0的 数据源配置
Class:ComboPooledDataSource
全限定名:com.mchange.v2.c3p0.ComboPooledDataSource
需要添加:com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar

二、JdbcTemplate案例

因为dbcp和C3p0大家都比较熟悉,下面我们就使用Spring的内置数据源进行演示。

2.1、简单案例

(如果看不懂,你叫人打我)

1、创建数据表:

 create table account(
 	id int primary key auto_increment,
 	name varchar(40),
 	money float
 )character set utf8 collate utf8_general_ci;
 
 insert into account(name,money) values('aaa',1000);
 insert into account(name,money) values('bbb',1000);

2、创建一个Maven项目:
在这里插入图片描述
3、pom.xml 引入jar包:
在这里插入图片描述
4、写一个测试类进行测试:
在这里插入图片描述
能正常运行,确定案例成功之后。接下来我们将数据库的配置换成注解或xml的配置。

5、创建一个Dao接口:
在这里插入图片描述
在这里插入图片描述
5、创建一个接口实现类AccountDaoImpl.java

package com.it.dao.impl;
import com.it.dao.IAccountDao;
import com.it.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;
/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",
                                                                    new BeanPropertyRowMapper<Account>(Account.class),
                                                                    accountId
                                                               );
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",
                                                                    new BeanPropertyRowMapper<Account>(Account.class),
                                                                    accountName
                                                                );
        if(accounts.isEmpty()){
            return null;
        }
        if(accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?,money=? where id=?",
                                        account.getName(),
                                        account.getMoney(),
                                        account.getId()
                                        );
    }
}

6、创建一个bean.xml配置文件:
在这里插入图片描述
在这里插入图片描述

7、编写测试类进行测试:
在这里插入图片描述

2.2、升级案例

接下来演示一下JdbcTemplate的CRUD和使用聚合函数的使用。
先来一波简单JdbcTemplate的CRUD的使用方法:
在这里插入图片描述

接下来是查询,在来里面选择两个常用的演示:
(接上面的测试类)

先定义一个返回集策略:
在这里插入图片描述
然后执行下面SQL:

1、查询账户余额大于1000的用户

List<Account> accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),1000f);
 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));

2、查询返回一行一列:


//查询返回一行一列(使用聚合函数,但不加group by子句)
Long count = jt.queryForObject("select count(*) from account where money > ?",Long.class,1000f);
System.out.println(count);
发布了22 篇原创文章 · 获赞 16 · 访问量 2894

猜你喜欢

转载自blog.csdn.net/qq_25083447/article/details/104729471