【Spring】Spring的数据库开发JDBCTemplate(批量操作、查询单条、多条)【附源码】

一、JDBCTemplate

Spring框架对JDBC进行了封装,使用JdbcTemplate类实现对数据库的资源操作和错误处理。JdbcTemplate继承抽象类JdbcAccessor,并实现了JdbcOperations接口
JdbcAccessor为子类提供了Datasource属性,用于获取数据库连接、数据库连接的缓冲池和分布式事务的支持,还可以作为数据库资源的标准接口;
Jdbcoperations定义了在JdbcTemplate类中进行CRUD(增删改查)等操作的集合。

Spring JDBC模块主要由4个包组成:core(核心包)、dataSource(数据源包)、object(对象包)和support(支持包)
dataSource的4个属性

属性名含义
driverClasName使用的数据库驱动名称,对应驱动jar包中的Driver类
url数据源所在地址
username访问数据库的用户名
password访问数据库的密码

二、JDBC Template的常用方法

所需要的jar包:Spring的5个基础jar包+数据库驱动jar包+jdbc的jar包+事务管理jar包+aop所需的jar包
在这里插入图片描述

1.execute()

execute(String sql):执行sql语句
以创建表为例演示:
(1)Spring配置文件:applicationContext.xml

<!--开启包扫描,对注解进行扫描,对Bean进行管理-->
<context:component-scan base-package="com.jd.jdbc"/>
<!--1.配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/springjdbc"/>
    <property name="username" value="root"/>
    <property name="password" value="12345678"/>
</bean>
<!--2.配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--注入Datasource-->
    <property name="dataSource" ref="dataSource"/>
</bean>

(2)测试方法:executeTest()

//execute(String sql)测试
@Test
public void executeTest(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
jdbcTemplate.execute("create table account(\n" +
        "    id int primary key auto_increment,\n" +
        "    username varchar(20),\n" +
        "    balance double\n" +
        ")");
System.out.println("账户表account创建成功...");
}

(3)执行结果,此时查询数据库表,account表已经完成创建:
在这里插入图片描述

2.update()

int update(String sql, Object…args):执行插入、更新和删除数据的操作,返回受影响的行数(第一个参数:sql语句;第二个:可变参数,填充sql语句中的占位符参数,不能为null)
实体类:Account.java

public class Account {
    private int id;//账户id
    private String username;//用户名
    private Double balance;//账户余额
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Double getBalance() {
        return balance;
    }
    public void setBalance(Double balance) {
        this.balance = balance;
    }
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", balance=" + balance +
                '}';
    }
}

Dao层接口:AccountDao.java

public interface AccountDao {
    //添加账户
    public int addAccount(Account account);
    //更新账户
    public int updateAccount(Account account);
    //删除账户
    public int deleteAccount(int id);
}

Dao层实现类:AccountDaoImpl .java

@Repository(value = "accountDao")
public class AccountDaoImpl implements AccountDao{
    //Dao中注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //添加账户
    @Override
    public int addAccount(Account account) {
        String sql = "insert into account(username,balance) values (?,?)";
        Object[] args = {account.getUsername(), account.getBalance()};
        //返回受影响的行数
        int rows = this.jdbcTemplate.update(sql, args);
        return rows;
    }
    //修改账户
    @Override
    public int updateAccount(Account account) {
        String sql = "update account set username = ?, balance = ? where id = ?";
        Object[] args = {account.getUsername(), account.getBalance(), account.getId()};
        int rows = this.jdbcTemplate.update(sql, args);
        return rows;
    }
    //删除账户
    @Override
    public int deleteAccount(int id) {
        String sql = "delete from account where id = ?";
        int rows = this.jdbcTemplate.update(sql, id);
        return rows;
    }
}

测试:
① 添加账户

//添加账户测试
@Test
public void addAccountTest(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    Account account = new Account();
    account.setId(2);
    account.setUsername("赵敏");
    account.setBalance(1000.0);
    //调用方法
    int rows = accountDao.addAccount(account);
    System.out.println("添加了"+rows+"行数据...");
}

在这里插入图片描述
② 修改账户

//修改账户测试
@Test
public void updateAccountTest(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    Account account = new Account();
    account.setId(2);
    account.setUsername("赵敏");
    account.setBalance(1000.0);
    //调用方法
    int rows = accountDao.updateAccount(account);
    System.out.println("修改了"+rows+"行数据...");
}

在这里插入图片描述
③ 删除账户

//删除账户测试
@Test
public void deleteAccountTest(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    int id = 2;
    //调用方法
    int rows = accountDao.deleteAccount(id);
    System.out.println("删除了"+rows+"行数据...");
}

在这里插入图片描述

3.query()

① queryForObject(String sql, Class< T> requiredType):查询某个值(如数量、最值、均值等)(第一个参数是sql语句,第二个参数是返回类型)
在接口AccountDao.java中声明查询单个值的方法:

//查询某个值(如数量、最值、均值等)
public int queryNum();

Dao层实现类:AccountDaoImpl .java

//查询某个值(如数量、最值、均值等)
@Override
public int queryNum() {
    String sql = "select count(*) from account";
    Integer num = this.jdbcTemplate.queryForObject(sql, Integer.class);
    return num;
}

测试:

//查询某个值(如数量、最值、均值等)
@Test
public void queryNumTest(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    int num = accountDao.queryNum();
    System.out.println(num);
}

在这里插入图片描述
② queryForObject(String sql, RowMapper rowMapper, Object…args):将args参数绑定到sql语句中,并通过RowMapper返回一个Object类型的单行记录
(第一个参数:sql语句;第二个参数:RowMapper,是接口,返回不同类型数据,使用这个接口里面实现类完成数据封装;第三个参数:sql语句值)
Dao层接口:AccountDao.java

//查询单行数据
public Account findAccountById(int id);

Dao层实现类:AccountDaoImpl .java

//查询单行数据
@Override
public Account findAccountById(int id) {
    String sql = "select id,username,balance from account where id = ?";
    //对数据进行封装
    RowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
    Account account = this.jdbcTemplate.queryForObject(sql, rowMapper, id);
    //返回封装的对象
    return account;
}

测试:

//查询单行数据
@Test
public void findAccountByIdTest(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    Account account = accountDao.findAccountById(5);
    System.out.println(account);
}

在这里插入图片描述
③ query(String sql, RowMapper rowMapper):执行sql,并通过RowMapper返回一个List类型的集合
Dao层接口:AccountDao.java

//查询多行数据
public List<Account> findAllAccount();

Dao层实现类:AccountDaoImpl.java

//查询多行数据
@Override
public List<Account> findAllAccount() {
    String sql = "select id,username,balance from account";
    RowMapper<Account> rowMapper = new BeanPropertyRowMapper<>(Account.class);
    List<Account> accountList = this.jdbcTemplate.query(sql, rowMapper);
    return accountList;
}

测试:

//查询多行数据
@Test
public void findAllAccountTest(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    List<Account> accountList = accountDao.findAllAccount();
    accountList.forEach(System.out::println);
}

在这里插入图片描述
此时实际数据库表中的数据:
在这里插入图片描述

4.批量操作

batchUpdate(String sql,List<0bject[]> batchArgs):对集合中对象数组进行批量添加、删除修改
(第一个参数:sql语句;第二个参数:使用List封装的对象数据)

(1)批量添加

Dao层接口:AccountDao.java

//批量添加数据
public void batchAddAccount(List<Object[]> batchArgs);

Dao层实现类:AccountDaoImpl.java

//批量添加数据
@Override
public void batchAddAccount(List<Object[]> batch) {
    String sql = "insert into account(username,balance) values (?,?)";
    int[] batchUpdate = this.jdbcTemplate.batchUpdate(sql, batch);
    System.out.println(Arrays.toString(batchUpdate));
}

测试:

//批量添加数据
@Test
public void batchAddAccountTest(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    //注意顺序和sql语句中字段的顺序一致
    Object[] o1 = {"张无忌",2000.0};
    Object[] o2 = {"小昭",1500.0};
    Object[] o3 = {"周芷若",1800.0};
    ArrayList<Object[]> batch = new ArrayList<>();
    batch.add(o1);
    batch.add(o2);
    batch.add(o3);
    //调用方法
    accountDao.batchAddAccount(batch);
}

此时数组存储的就是添加操作返回的行数:
在这里插入图片描述
查询表中的数据,已经添加:
在这里插入图片描述

(2)批量更新

Dao层接口:AccountDao.java

//批量更新数据
public void batchUpdateAccount(List<Object[]> batchArgs);

Dao层实现类:AccountDaoImpl.java

//批量更新数据
@Override
public void batchUpdateAccount(List<Object[]> batchArgs) {
    String sql = "update account set username = ?, balance = ? where id = ?";
    int[] batchUpdate = this.jdbcTemplate.batchUpdate(sql, batchArgs);
    System.out.println(Arrays.toString(batchUpdate));
}

测试:

//批量更新数据
@Test
public void batchUpdateAccountTest(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    //注意顺序和sql语句中字段的顺序一致
    Object[] o1 = {"令狐冲",800.0,1};
    Object[] o2 = {"任我行",600.0,2};
    Object[] o3 = {"任盈盈",800.0,3};
    ArrayList<Object[]> batch = new ArrayList<>();
    batch.add(o1);
    batch.add(o2);
    batch.add(o3);
    //调用方法
    accountDao.batchUpdateAccount(batch);
}

在这里插入图片描述
查询表中的数据,已经更新:
在这里插入图片描述

(3)批量删除

Dao层接口:AccountDao.java

//批量添删除数据
public void batchDeleteAccount(List<Object[]> batchArgs);

Dao层实现类:AccountDaoImpl.java

//批量删除数据
@Override
public void batchDeleteAccount(List<Object[]> batchArgs) {
    String sql = "delete from account where id = ?";
    int[] batchUpdate = this.jdbcTemplate.batchUpdate(sql, batchArgs);
    System.out.println(Arrays.toString(batchUpdate));
}

测试:

//批量删除数据
@Test
public void batchDeleteAccountTest(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
    //注意顺序和sql语句中字段的顺序一致
    Object[] o1 = {1};
    Object[] o2 = {2};
    Object[] o3 = {3};
    ArrayList<Object[]> batch = new ArrayList<>();
    batch.add(o1);
    batch.add(o2);
    batch.add(o3);
    //调用方法
    accountDao.batchDeleteAccount(batch);
}

在这里插入图片描述
查询表中的数据,已经删除:
在这里插入图片描述

  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_46081857

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值