【Spring】第四课 Spring框架以及JDBCTemplate的使用

概念

本文结合前面所讲授的Spring框架的知识点基础上,教授JDBCTemplate的使用。

 

项目创建步骤

创建项目,在WEB-INF文件夹下新建lib文件夹,将以下jar包导入,并关联至项目

在项目中新建resources资源文件夹将applicationContext.xml主配置文件导入,并转换成项目的资源文件夹

在src文件夹中创建测试类的包com.spring.test,新建SpringTest类。

package com.spring.test;

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

import java.util.List;
import java.util.Map;

public class SpringTest {

    JdbcTemplate jt = null;

    public void init() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        jt = ac.getBean("jt", JdbcTemplate.class);
    }

    @Test
    public void one() {
        //使用JDBCTemplate连接数据库一定需要四个参数
        //配置数据库连接池
        DriverManagerDataSource dmds = new DriverManagerDataSource();
        //设置数据库驱动程序
        dmds.setDriverClassName("com.mysql.jdbc.Driver");
        //设置连接数据库的访问地址
        dmds.setUrl("jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8");
        //设置登录数据库的用户名
        dmds.setUsername("root");
        //设置登录数据库的密码
        dmds.setPassword("admin");

        //创建JDBCTemplate对象,并把连接池参数添加进去
        JdbcTemplate jt = new JdbcTemplate(dmds);
        //可以执行增删改查的sql语句操作
        //给银行账户表中添加一个账户信息
        int i = jt.update("insert into account values(?,?,?,?,?,?)",
                new Object[]{888889, "000000", "余老师", "360105202204061611", 12000000, "2022-04-06 13:54:01"});
        if (i > 0)
            System.out.println("账户添加成功");
    }



}

本文操作连接的数据库是前文中定义的银行账户管理系统的数据库表文件。【MyBatis】第五课 银行账户管理系统网站开发 

接着,我们将连接数据库的连接池的代码转换成Spring框架主配置文件中进行创建对象,applicationContext.xml主配置文件中代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<!--DriverManagerDataSource dmds=new DriverManagerDataSource();-->
	<bean id="dmds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
			<!--dmds.setDriverClassName("com.mysql.jdbc.Driver");-->
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<!--dmds.setUrl("jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8");-->
		<property name="url" value="jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=UTF-8"></property>
		<!--dmds.setUsername("root");-->
		<property name="username" value="root"></property>
		<!--dmds.setPassword("admin");-->
		<property name="password" value="admin"></property>
	</bean>

	<!--JdbcTemplate jt=new JdbcTemplate(dmds);-->
	<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
		<constructor-arg name="dataSource" ref="dmds"></constructor-arg>
	</bean>

</beans>

 接着在测试类中定义测试方法,通过加载获得主配置文件中的对象来操作JDBCTemplate,完成增删改查的各种操作,其代码如下:

package com.spring.test;

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

import java.util.List;
import java.util.Map;

public class SpringTest {

    JdbcTemplate jt = null;

    public void init() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        jt = ac.getBean("jt", JdbcTemplate.class);
    }

    @Test
    public void one() {
        //使用JDBCTemplate连接数据库一定需要四个参数
        //配置数据库连接池
        DriverManagerDataSource dmds = new DriverManagerDataSource();
        //设置数据库驱动程序
        dmds.setDriverClassName("com.mysql.jdbc.Driver");
        //设置连接数据库的访问地址
        dmds.setUrl("jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8");
        //设置登录数据库的用户名
        dmds.setUsername("root");
        //设置登录数据库的密码
        dmds.setPassword("admin");

        //创建JDBCTemplate对象,并把连接池参数添加进去
        JdbcTemplate jt = new JdbcTemplate(dmds);
        //可以执行增删改查的sql语句操作
        //给银行账户表中添加一个账户信息
        int i = jt.update("insert into account values(?,?,?,?,?,?)",
                new Object[]{888889, "000000", "余老师", "360105202204061611", 12000000, "2022-04-06 13:54:01"});
        if (i > 0)
            System.out.println("账户添加成功");
    }

    @Test
    public void two() {
        init();
        int i = jt.update("insert into account values(?,?,?,?,?,?)",
                new Object[]{888899, "000000", "余老师", "360105202204061611", 12000000, "2022-04-06 13:54:01"});
        if (i > 0)
            System.out.println("账户添加成功");
    }

    @Test
    public void three(){
        init();
        int i = jt.update("update account set balance=? where id=?", new Object[]{36000000, 888899});
        if (i>0)
            System.out.println("修改成功");
    }

    @Test
    public void four(){
        init();
        int i = jt.update("delete from account where id=?", new Object[]{888889});
        if (i>0)
            System.out.println("删除成功");
    }

    @Test
    public void five(){
        init();
        //查询总共有多少个账户
        //第一个参数是表示sql语句
        //第二个参数是返回值的类型对应的类
        int i = jt.queryForObject("select count(*) from account", Integer.class);
        System.out.println("查询到账户的总个数为:"+i);
        //查询账号888888的账户余额是多少
        Double aDouble = jt.queryForObject("select balance from account where id=?",
                                new Object[]{888888}, Double.class);
        System.out.println("账户余额为:"+aDouble);
        //查询账号888888的账户姓名
        String s = jt.queryForObject("select name from account where id=?",
                new Object[]{888888}, String.class);
        System.out.println(s);

    }

    @Test
    public void six(){
        init();
        //查询的是一条数据,多个字段
        Map<String, Object> map = jt.queryForMap("select * from account where id=?",
                new Object[]{888888});
        map.forEach((k,v)-> System.out.println(k+":"+v));
    }

    @Test
    public void seven(){
        init();
        //JDBCTemplate类中没有提供将一条数据转换成实体类的方法
//        Account account = jt.queryForObject("select * from account where id=?",
//                new Object[]{888888}, Account.class);

        Account account=jt.query("select * from account where id=?",
                new Object[]{888888},new BeanPropertyRowMapper<>(Account.class)).get(0);

        System.out.println(account.toString());
    }

    @Test
    public void eight(){
        //查询整张表的数据,多条数据
        init();
        List<Map<String, Object>> maps = jt.queryForList("select * from account");
        maps.forEach(map-> System.out.println(map));

        List<Account> accounts=jt.query("select * from account ",
                new BeanPropertyRowMapper<>(Account.class));
        accounts.forEach(a-> System.out.println(a.toString()));
    }

}

其中所需要用到的实体类代码如下:

package com.spring.test;

public class Account {
    private int id;
    private String password;
    private String name;
    private String personid;
    private double balance;
    private String opendate;

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", password='" + password + '\'' +
                ", name='" + name + '\'' +
                ", personid='" + personid + '\'' +
                ", balance=" + balance +
                ", opendate='" + opendate + '\'' +
                '}';
    }

    public Account() {
    }

    public Account(int id, String password, String name, String personid, double balance, String opendate) {
        this.id = id;
        this.password = password;
        this.name = name;
        this.personid = personid;
        this.balance = balance;
        this.opendate = opendate;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPersonid() {
        return personid;
    }

    public void setPersonid(String personid) {
        this.personid = personid;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public String getOpendate() {
        return opendate;
    }

    public void setOpendate(String opendate) {
        this.opendate = opendate;
    }
}

使用JDBCTemplate操作不同的SQL语句得到的数据保存结果的测试方法,读者可编写代码自行运行,查看效果。

总结

本次对于Spring框架的学习就介绍到这里,Spring框架的强大远远不止如此,读者需要更深入的学习该框架,才能在企业中工作中学习中做到游刃有余!!!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

笔触狂放

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

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

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

打赏作者

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

抵扣说明:

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

余额充值