Spring 学习之路-- Spring的数据库开发(JDBC Template)学习笔记

Spring的数据库开发

一、jdbcTemplate相关概念

1 jdbc模板,定义了操作数据库的方法

2 继承关系:继承了jdbcAccessor 实现了jdbcOperations

jdbcAccessor:

dataSource : 数据源 ,数据库的连接和事务

​ 其主要功能是获取数据库连接,还可以引入对数据库连接的缓冲池和分布式事务的支持,它可以作为访问数据库资源的标准接口。

datasource配置中的4个属性

SQLExceptionTranslator:sql异常时对应的翻译

​ 该接口负责对SQLException进行转译工作。通过必要的设置获取SQLExceptionTranslator中的方法,可以使JdbcTemplate在需要处理SQLException时,委托SQLExceptionTranslator的实现类来完成相关的转译工作。

jdbc模块的组成
JdbcOperations:

update() 增删改的sql语句
query() 查询
execute() 建表有关的sql

dao —>jdbcTemplate—>datasource

二、案例实现

1.创建数据库

​ 在 MYSQL中,创建一个名为 spring的数据库

2.创建web项目,导入jar包

​ 导入 JdbcTemplate所需JAR包到项目的lib目录中,并发布到类路径下。

所需jar包地址

3.配置文件 applicationContext

​ 在 src下,创建配置文件 applicationContext.xml,并编写相关配置,在该文件中配置id为 datasource的数据源Bean和id为 jdbctemplate的JDBC模板Bean,并将数据源注入到JDBC模板中。

<?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-4.3.xsd">
    <!--配置数据源-->
    <bean id="dateSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!--配置数据库驱动-->
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <!--配置数据库url-->
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <!--配置数据库用户名-->
        <property name="username" value="root"/>
        <!--配置数据库密码-->
        <property name="password" value="123456"/>
    </bean>
    <!--配置JDBC模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--默认使用数据源-->
        <property name="dataSource" ref="dateSource"/>
    </bean>
    <!--配置注入类-->
    <bean id="userDao" class="com.soft.jdbc.AccountImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
</beans>

4.创建Account类

​ 在该web项目下的 com.soft.jdbc 包中创建 Account类,在该类中定义id,username和 balance属性,以及其对应的 getter/setter方法及重写tostring方法。

package com.soft.jdbc;

public class Account {

    private int 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 +
                '}';
    }
}

5.创建接口 IAccountDao

​ 在 com.soft.jdbc 包中,创建接口 IAccountDao,并在接口中定义添加、更新、删除账户和查询的方法。

package com.soft.jdbc;

import java.util.List;

public interface IAccountDao {

    public int addAccount(Account account);

    public int updateAccount( Account account);

    public int deleteAccount(Account account);
    
    public Account findAccountById(int id);

    public List<Account> findAllAccount();
}

6.创建接口的实现类 Accountdaolmpl

​ 在 com.soft.jdbc 包中,创建 IAccountDao接口的实现类 Accountdaolmpl,并在类
中实现添加、更新、删除账户和两种查询的方法。

package com.soft.jdbc;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class AccountDaoImpl implements  IAccountDao {
	//声明属性及其setter方法
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    //添加方法
    public int addAccount(Account account) {
        String sql = "insert into account2 (username,balance) values (?,?)";
        Object[] obj = new Object[]{account.getUsername(),account.getBalance()};
        int i = jdbcTemplate.update(sql, obj);
        return i;
    }

    @Override
    //更新方法
    public int updateAccount(Account account) {
        String sql = "update account2 set username=?,balance=? where id=?";
        int i = jdbcTemplate.update(sql, account.getUsername(), account.getBalance(), account.getId());
        return i;
    }

    @Override
    //删除方法
    public int deleteAccount(int id) {
        String sql = "delete from account2 where id =?";
        int i = jdbcTemplate.update(sql, id);
        return i;
    }
    
    @Override
    //通过Id查询方法
    public Account findAccountById(int id) {
        String sql = "select * from account2 where id=?";
        Account account = jdbcTemplate.queryForObject(sql, new 			BeanPropertyRowMapper<>(Account.class), id);
        return  account;
    }

    @Override
    //查询整张表
    public List<Account> findAllAccount() {
        String sql = "select * from account2";
        List<Account> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Account.class));
        return list;
    }
}

7.创建测试类jdbcTest

​ 在测试类jdbcTest中,添加一个测试方法若干,这些方法主要用于创建表,添加用户账户信息,更新用户账户信息,删除用户账户信息,查询用户账户信息,其代码如下所示。

Junit是一个进行单元测试的开源框架

@Test就是 Junit4用于测试的注解,要测试哪个方法,只需要在相应测试的方法上添加此注解即可。

package com.soft.jdbc;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.Map;

public class jdbcTest {
/*	//建表测试
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appllicationContext.xml");
        JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
        String sql = "create table account2 (id int primary key auto_increment,username varchar(32),balance double)";
        jdbcTemplate.execute(sql);
        System.out.println("建表成功");
    }*/

    @Test
    //添加用户信息
    public void test01(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appllicationContext.xml");
        IAccountDao dao = (IAccountDao) applicationContext.getBean("accountDao");
        Account account = new Account();
        account.setUsername("lina");
        account.setBalance(1000);
        int i = dao.addAccount(account);
        if(i>0){
            System.out.println("插入了"+i+"条数据");
        }
    }

    @Test
    //更新用户信息
    public void test02(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appllicationContext.xml");
        IAccountDao dao = (IAccountDao) applicationContext.getBean("accountDao");
        Account account = new Account();
        account.setId(2);
        account.setUsername("lina02");
        account.setBalance(2000);
        int i = dao.updateAccount(account);
        if(i>0){
            System.out.println("修改了"+i+"条数据");
        }else {
            System.out.println("修改失败");
        }
    }

    @Test
    //通过Id查询用户信息
    public void test03(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appllicationContext.xml");
        IAccountDao dao = (IAccountDao) applicationContext.getBean("accountDao");
        Account account = dao.findAccountById(1);
        System.out.println(account);
    }

    @Test
    //查询整张表
    public void test04(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appllicationContext.xml");
        IAccountDao dao = (IAccountDao) applicationContext.getBean("accountDao");
        List<Account> list = dao.findAllAccount();
        System.out.println(list);
    }
    
    @Test
    //删除某条用户信息,通过Id
    public void test05(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appllicationContext.xml");
        IAccountDao dao = (IAccountDao) applicationContext.getBean("accountDao");
        int i = dao.deleteAccount(1);
        System.out.println("删除了"+i+"条数据");
    }
}

8.运行结果

​ 这里以测试addAccount为例,其他方法同理,不予赘述。

测试前数据库表数据:

测试后数据库表数据:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

liangpi_hero

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

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

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

打赏作者

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

抵扣说明:

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

余额充值