Spring中的 JdbcTemplate

JdbcTemplate 概述

JdbcTemplate 是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。
spring 框架为我们提供了很多 的操作模板类。
比如操作关系型数据的: JdbcTemplate HibernateTemplate
比如操作 nosql 数据库的: RedisTemplate
比如操作消息队列的: JmsTemplate


下面我们以账户的增删改查为例,进行案例的讲解
首先得创建这样一张表

create table account(id int primary key auto_increment,name varchar(20),money float);

然后插入两条数据

insert into account values(null,"jack",1000),(null,"tina",1000);

导入相关jar包坐标

<packaging>jarpackaging>
    <dependencies>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.11version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.0.9version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.0.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.0.3.RELEASEversion>
        dependency>

    dependencies>

编写账户实体类

Account.java

package domain;

import java.io.Serializable;

/**
 * 账户的实体类
 */
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接口

IAccountDao.java

package dao;

import domain.Account;

import java.util.List;

/**
 * 账户的持久层接口
 */
public interface IAccountDao {

    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 根据ID查询一个
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 保存
     * @param account
     */
    int saveAccount(Account account);

    /**
     * 更新
     * @param account
     */
    int updateAccount(Account account);

    /**
     * 删除
     * @param acccountId
     */
    int deleteAccount(Integer acccountId);

    /**
     * 根据名称查询账户
     * @param accountName
     * @return  如果有唯一的一个结果就返回,如果没有结果就返回null
     *          如果结果集超过一个就抛异常
     */
    Account findAccountByName(String accountName);
}

编写DAO实现类

AccountDaoImpl.java

package dao.impl;

import dao.IAccountDao;
import domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl implements IAccountDao {


    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public List<Account> findAllAccount() {
        String sql = "select * from account";
        List<Account> accounts = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
        return accounts;
    }

    public Account findAccountById(Integer accountId) {
        String sql = "select * from account where id=?";
        List<Account> accounts = jdbcTemplate.query(sql,new BeanPropertyRowMapper<Account>(Account.class),accountId);
        if (accounts.isEmpty()){
            return null;
        }
        return accounts.get(0);
    }

    public int saveAccount(Account account) {
        String sql = "insert into account values(?,?,?)";
        return jdbcTemplate.update(sql, account.getId(), account.getName(), account.getMoney());
    }

    public int updateAccount(Account account) {
        String sql = "update account set id=?,name=?,money=? where id=?";
        return jdbcTemplate.update(sql, account.getId(), account.getName(), account.getMoney(), account.getId());

    }

    public int deleteAccount(Integer acccountId) {
        String sql = "delete from account where id=?";
        return jdbcTemplate.update(sql, acccountId);
    }

    public Account findAccountByName(String accountName) {
        String sql = "select * from account where name=?";
        List<Account> accounts = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (accounts.size()>1)
        {
            throw new RuntimeException("查询到记录数大于1");
        }
        if (accounts.isEmpty())
        {
            return null;
        }
        return accounts.get(0);
    }
}

编写账户Service接口

IAccountService.java

package service;

import domain.Account;

import java.util.List;

public interface IAccountService {

    List<Account> findAllAccount();

    Account findAccountById(Integer accountId);

    int saveAccount(Account account);

    int updateAccount(Account account);

    int deleteAccount(Integer acccountId);

    Account findAccountByName(String accountName);

    boolean transformAccount(Account a1,Account a2,int money);
}

编写Service实现类

AccountServiceImpl.java

package service.impl;

import dao.IAccountDao;
import domain.Account;
import service.IAccountService;
import java.util.List;

public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    public int saveAccount(Account account) {
        return accountDao.saveAccount(account);
    }

    public int updateAccount(Account account) {
        return accountDao.updateAccount(account);
    }

    public int deleteAccount(Integer acccountId) {
        return accountDao.deleteAccount(acccountId);
    }

    public Account findAccountByName(String accountName) {
        return accountDao.findAccountByName(accountName);
    }

    /**
     * 转账
     * @param a1 转账方
     * @param a2 收款方
     * @param money 转账金额
     * @return
     */
    public boolean transformAccount(Account a1, Account a2, int money) {
        a1.setMoney(a1.getMoney()-money);
        a2.setMoney(a2.getMoney()+money);
        updateAccount(a1);
        updateAccount(a2);
        return true;
    }
}

编写 spring 的配置文件


<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
  ">

    <bean id="accountServiceImpl" class="service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDaoImpl">property>
    bean>

    
    <bean id="accountDaoImpl" class="dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate">property>
    bean>
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
          destroy-method="close">
        
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver">property>
        <property name="url" value="jdbc:mysql://localhost:3306/class_db?useUnicode=true&serverTimezone=GMT&useSSL=false">property>
        <property name="username" value="root">property>
        <property name="password" value="qwe123">property>
        
        <property name="filters" value="stat" />
        
        <property name="maxActive" value="20" />
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" />

        
        <property name="maxWait" value="60000" />

        
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        
        <property name="poolPreparedStatements" value="true" />
        <property name="maxOpenPreparedStatements" value="20" />
    bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource">property>
    bean>
beans>

测试代码

import domain.Account;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.IAccountService;

import java.util.List;

public class testdemo {

    private ApplicationContext ac;
    private IAccountService as;

    @Before
    public void init()
    {
        ac = new ClassPathXmlApplicationContext("bean.xml");
        as  = ac.getBean("accountServiceImpl", IAccountService.class);
    }

    @Test
    public void testFindall()
    {
        List<Account> allAccount = as.findAllAccount();
        for (Account account : allAccount) {
            System.out.println(account);
        }
    }
    @Test
    public void testFindbyid()
    {
        Account accountById = as.findAccountById(1);
        System.out.println(accountById);
    }
    @Test
    public void testFindbyname()
    {
        Account jack = as.findAccountByName("jack");
        System.out.println(jack);
    }
    @Test
    public void testSave()
    {
        Account test = new Account();
        test.setName("test");
        test.setMoney(2000f);
        as.saveAccount(test);
    }
    @Test
    public void testUpdate()
    {
        Account account = as.findAccountById(10);
        account.setMoney(3000f);
        account.setName("test1");
        as.updateAccount(account);
    }
    @Test
    public void testDelete()
    {
        as.deleteAccount(10);
    }
    @Test
    public void testTransformaccount()
    {
        Account account1 = as.findAccountById(1);
        Account account2 = as.findAccountById(2);
        as.transformAccount(account1,account2,100);
    }
}

以上就是今天分享的关于Spring中的 JdbcTemplate增删改查的使用了。希望大家能够有所收获,欢迎关注。

你可能感兴趣的:(spring)