Spring 中JdbcTemplate的使用

1、项目目录以及数据库表的信息

在这里插入图片描述
在这里插入图片描述

2、目录源代码

pox.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring</groupId>
    <artifactId>jdbcTemplate</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
    </dependencies>


</project>

Account类

package com.spring.domain;

import java.io.Serializable;

public class Account implements Serializable {
    private int id;
    private String name;
    private float money;

    public int getId() {
        return id;
    }

    public void setId(int 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 +
                '}';
    }
}

jdbcDemo类

package com.spring.jdbcTemplate;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * jdbcTemplate的最基本用法
 */
public class jdbcDemo {
    public static void main(String[] args) {
        //准备数据源,spring内置数据源
        DriverManagerDataSource dm = new DriverManagerDataSource();
        dm.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dm.setUrl("jdbc:mysql://localhost:3306/jdbcTemplate?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT");
        dm.setUsername("root");
        dm.setPassword("111111");
//        1、创建JdbcTemplate对象
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(dm);
//        2、执行操作
        jt.execute("insert into account(name,money)values ('bbb',100)");
    }

}

执行结果:
在这里插入图片描述

3、jdbcTemplate在Spring的IOC使用

添加bean.xml文件配置

<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-2.5.xsd">

    <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.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/jdbcTemplate?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT"></property>
        <property name="username" value="root"></property>
        <property name="password" value="111111"></property>
    </bean>
</beans>

修改jdbcDemo:

package com.spring.jdbcTemplate;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * jdbcTemplate的最基本用法
 */
public class jdbcDemo {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//        1、创建JdbcTemplate对象
        JdbcTemplate jt =(JdbcTemplate) ac.getBean("jdbcTemplate");
//        2、执行操作
        jt.execute("insert into account(name,money)values ('bbb',100)");
    }

}

3、jdbcTemplate的CRUD操作

jdbcDemo类

package com.spring.jdbcTemplate;

import com.spring.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * jdbcTemplate的最基本用法
 */
public class jdbcDemo {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        JdbcTemplate jt =(JdbcTemplate) ac.getBean("jdbcTemplate");
//        保存
        jt.update("insert  into account(name,money)values (?,?)","qq","1000");
//        更新
        jt.update("update account set name=?,money=? where id=?","asd",1000,1);
//        删除
        jt.update("delete from account where id = ?","1");
//        查询所有
        List<Account> list = jt.query("select * from account where money > ?",new AccountRowMapper(),90f);
        for(Account account:list){
            System.out.println(account);
        }
//        查询单个
        List<Account> one= jt.query("select * from account where id=?",new AccountRowMapper(),2);
        System.out.println(list.isEmpty()?"没有":list.get(0));
    }
}

class AccountRowMapper implements RowMapper<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;
    }
}
  • 其中这里的查询所有需要创建一个AccountRowMapper类,这个类用于封装Account,然后呢返回给Spring,再有Spring封装成一个集合。

3、jdbcTemplate在Dao层的实现

在这里插入图片描述
IAccountDaoImpl类

package com.spring.dao.impl;

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

import java.util.List;

public class IAccountDaoImpl implements IAccountDao {
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return 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),
                accountId);
        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),
                accountName);
        if(accounts.isEmpty())
            return null;
        if(accounts.size() > 1)
            throw new RuntimeException("结果集不唯一");
        return accounts.get(0);
    }
    public void updateAccount(Account account) {
        jdbcTemplate.update("" +
                "update account set name=?,money=? where id=?",
                account.getName(),account.getMoney(),account.getId());

    }
}

bean.xml中增加一条配置信息

 <bean id="accountDao" class="com.spring.dao.impl.IAccountDaoImpl">
    <property name="jdbcTemplate" ref="jdbcTemplate"></property>
 </bean>

调用

public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        IAccountDao iAccountDao = (IAccountDao) ac.getBean("accountDao");
        Account account = iAccountDao.findAccountById(2);
        System.out.println(account);
}

在这里插入图片描述

了解:

我们还可以简化代码的方式,如果实现类很多,那么jdbctemplate和dataSource的set和get方法就会有很多的冗余,对该实现类进一步优化。通过继承JdbcDaoSupport这个类,实现简化代码。这个类中含有了jdbctemplate和dataSource。我们只需要用surper去调用这两个的get方法就可以。这种方法对于注解开发是不行的。

package com.spring.dao.impl;

import com.spring.dao.IAccountDao;
import com.spring.domain.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

public class IAccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

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

    }
    public Account findAccountByName(String accountName) {
        List<Account> accounts =  super.createJdbcTemplate(super.getDataSource()).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);
    }
    public void updateAccount(Account account) {
        super.createJdbcTemplate(super.getDataSource()).update("" +
                "update account set name=?,money=? where id=?",
                account.getName(),account.getMoney(),account.getId());

    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值