[Spring] Spring5——JdbcTemplate 简介

news2024/9/17 7:35:07

目录

一、JdbcTemplate 概述

1、什么是 JdbcTemplate

2、准备运行环境

二、添加功能

1、示例

三、修改和删除功能

1、示例

四、查询功能

1、查询记录数

2、查询返回 bean 对象

3、查询返回集合

4、测试

五、批量增删改功能

1、批量添加

2、批量修改

3、批量删除


一、JdbcTemplate 概述

1、什么是 JdbcTemplate

Spring 框架对 JDBC 进行封装,形成一个 Spring 风格的模板,使用 JdbcTemplate 方便实现对数据库操作。

2、准备运行环境

(1)添加依赖(导入 jar 包或使用 maven)

这里使用 maven:

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.6.0</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.3.22</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>5.3.22</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.3.22</version>
</dependency>

(2)在 spring 配置文件配置数据库连接池

依据介绍 IOC 的文章中的操作:

  • 可以选择将数据库信息写死在 xml 中;
  • 也可以使用 placeholder 标签引入 properties 配置文件;

(3)把前面配置好的数据库连接池注入到 JdbcTemplate 对象的 DataSource 属性

  • 由于 JdbcTemplate 源码中使用的是 set 方法,因此这里需要使用 <property> 来进行注入。
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 注解扫描 -->
    <context:component-scan base-package="com.demo"></context:component-scan>

    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="org.postgresql.Driver"></property>
        <property name="url" value="jdbc:postgresql://localhost:5432/MyDatabase"></property>
        <property name="username" value="postgres"></property>
        <property name="password" value="123456"></property>
    </bean>

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

(4)创建 Service 类,创建 Dao 类,向 dao 注入 jdbcTemplate 对象

(4-1)Service 类

package com.demo.service.impl;

import com.demo.dao.UserDao;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    @Qualifier(value = "userDaoImpl")
    private UserDao userDao;
}

(4-2)Dao 类

package com.demo.dao.impl;

import com.demo.dao.UserDao;
import org.springframework.beans.factory.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    @Qualifier(value = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;
}

(5)测试代码

import com.demo.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DruidTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Druid.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        System.out.println(userService);
    }
}

二、添加功能

实际上 JdbcTemplate 与 dbutil 类似,都是第三方的数据库操作的封装类,因此使用上也是差不多的,不再做特别说明。

1、示例

创建名为 MyDatabase 的数据库,创建一个名为 MyUser 的表。

首先创建一个 bean 对象,然后编写对应的 dao 层和 service 层,在 dao 层中使用 JdbcTemplate  的 update 方法来做添加操作。

(1)代码

(1-1)User

package com.demo.pojo;

public class User {
    private Integer Id;
    private String username;
    private String Status;

    public User() {
    }

    public User(Integer id, String username, String status) {
        Id = id;
        this.username = username;
        Status = status;
    }

    @Override
    public String toString() {
        return "User{" +
                "Id=" + Id +
                ", username='" + username + '\'' +
                ", Status='" + Status + '\'' +
                '}';
    }

    public Integer getId() {
        return Id;
    }

    public void setId(Integer id) {
        Id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getStatus() {
        return Status;
    }

    public void setStatus(String status) {
        Status = status;
    }
}

(1-2)UserDao 与 UserService

  • 在 dao 进行数据库添加操作;
  • 调用 JdbcTemplate 对象里面 update 方法实现添加操作;
package com.demo.dao.impl;

import com.demo.dao.UserDao;
import com.demo.pojo.User;
import org.springframework.beans.factory.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    @Qualifier(value = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    public int addUser(User user) {
        // 这里不传 id 是因为设置了 id 自增。
        String sql = "insert into \"MyUser\"(username, status) values(?, ?);";
        return jdbcTemplate.update(sql, user.getUsername(), user.getStatus());
    }

}
package com.demo.service.impl;

import com.demo.dao.UserDao;
import com.demo.pojo.User;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    @Qualifier(value = "userDaoImpl")
    private UserDao userDao;

    public void addUser(User user) {
        userDao.addUser(user);
    }
}

(1-3)测试代码

import com.demo.pojo.User;
import com.demo.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DruidTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Druid.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.addUser(new User("wyt", "statusA"));
    }
}

(2)运行结果

三、修改和删除功能

修改和删除的做法,基本与添加操作一致,都是使用 update 方法。

1、示例

(1)代码

(1-1)UserDao 与 UserService

package com.demo.dao.impl;

import com.demo.dao.UserDao;
import com.demo.pojo.User;
import org.springframework.beans.factory.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    @Qualifier(value = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    public int addUser(User user) {
        String sql = "insert into \"MyUser\"(username, status) values(?, ?);";
        return jdbcTemplate.update(sql, user.getUsername(), user.getStatus());
    }

    public int updateUser(User user) {
        String sql = "update \"MyUser\" set username=?, status=? where id=?";
        return jdbcTemplate.update(sql, user.getUsername(), user.getStatus(), user.getId());
    }

    public int deleteUserById(Integer id) {
        String sql = "delete from \"MyUser\" where id=?";
        return jdbcTemplate.update(sql, id);
    }

}
package com.demo.service.impl;

import com.demo.dao.UserDao;
import com.demo.pojo.User;
import com.demo.service.UserService;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    @Qualifier(value = "userDaoImpl")
    private UserDao userDao;

    public void addUser(User user) {
        userDao.addUser(user);
    }

    public void updateUser(User user) {
        userDao.updateUser(user);
    }

    public void deleteUserById(Integer id) {
        userDao.deleteUserById(id);
    }
}

(1-2)测试代码

  • 先添加两个 User,然后修改第 2 个 User,删除第 1 个 User
import com.demo.pojo.User;
import com.demo.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DruidTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Druid.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);

        userService.addUser(new User(null, "wyt", "statusA"));
        User tmp = new User(null, "gyt", "statusB");
        userService.addUser(tmp);

        tmp.setStatus("statusC");
        userService.updateUser(tmp);

        userService.deleteUserById(1);
    }
}

(2)运行结果

四、查询功能

1、查询记录数

@Override
public int selectCount() {
    String sql = "select count(*) from \"MyUser\"";
    return jdbcTemplate.queryForObject(sql, Integer.class);
}

2、查询返回 bean 对象

RowMapper 是接口,针对返回不同类型数据,使用这个接口的实现类完成数据封装。

@Override
public User queryForUserById(Integer id) {
    String sql = "select * from \"MyUser\" where id=?";
    return (User) jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
}

3、查询返回集合

@Override
public List<User> queryForAllUsers() {
    String sql = "select * from \"MyUser\"";
    return (List<User>) jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
}

4、测试

上面三种查询都是 dao 层的,还需要再 service 层中调用,这里就不写出来了。

(1)代码

import com.demo.pojo.User;
import com.demo.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class DruidTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Druid.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);

        userService.addUser(new User(null, "wyt", "statusA"));
        userService.addUser(new User(null, "gyt", "statusB"));

        System.out.println("行数:" + userService.selectCount());
        System.out.println(userService.queryForUserById(2));

        List<User> userList = userService.queryForAllUsers();
        System.out.println(userList);
    }
}

(2)输出结果

五、批量增删改功能

前面的 insert、delete、update 都只能操作一条记录,而批量操作就可以做到 insert、delete、update 多条记录。

1、批量添加

使用 batchUpdate,传入 Object 数组的 List 集合,那么该方法就会遍历 List,将每一个 Object 数组执行 sql 语句。

(1)代码

(1-1)UserDao

@Override
public void batchAddUsers(List<Object[]> batchArgs) {
    String sql = "insert into \"MyUser\"(username, status) values(?,?)";
    int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
}

(1-2)测试代码

import com.demo.pojo.User;
import com.demo.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class DruidTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Druid.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);

        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 = {"wyt", "statusA"}; batchArgs.add(o1);
        Object[] o2 = {"gyt", "statusB"}; batchArgs.add(o2);
        Object[] o3 = {"lyt", "statusC"}; batchArgs.add(o3);

        userService.batchAddUsers(batchArgs);

        System.out.println(userService.queryForAllUsers());
    }
}

(2)输出结果

2、批量修改

(1)代码

(1-1)UserDao

@Override
public void batchUpdateUsers(List<Object[]> batchArgs) {
    String sql = "update \"MyUser\" set username=?, status=? where id=?";
    int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
}

(1-2)测试代码

import com.demo.pojo.User;
import com.demo.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class DruidTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Druid.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);

        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 = {"wyt001", "statusA", 1}; batchArgs.add(o1);
        Object[] o2 = {"gyt110", "statusB", 2}; batchArgs.add(o2);
        Object[] o3 = {"lyt101", "statusC", 3}; batchArgs.add(o3);

        userService.batchUpdateUsers(batchArgs);

        System.out.println(userService.queryForAllUsers());
    }
}

(2)运行结果

3、批量删除

(1)代码

(1-1)UserDao

@Override
public void batchDeleteUsersById(List<Object[]> batchArgs) {
    String sql = "delete from \"MyUser\" where id=?";
    int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs); // 返回影响行数
}

(1-2)测试代码

  • 将 id 为 1、2 的删除。
import com.demo.pojo.User;
import com.demo.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class DruidTest {
    @Test
    public void test() {
        ApplicationContext context = new ClassPathXmlApplicationContext("Druid.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);

        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 = {1}; batchArgs.add(o1);
        Object[] o2 = {2}; batchArgs.add(o2);

        userService.batchDeleteUsersById(batchArgs);

        System.out.println(userService.queryForAllUsers());
    }
}

(2)输出结果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1061738.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Context应用上下文理解

文章目录 一、Context相关类的继承关系Context类ContextIml.java类ContextWrapper类ContextThemeWrapper类 二、 什么时候创建Context实例创建Context实例的时机 小结 Context类 &#xff0c;说它熟悉&#xff0c;是应为我们在开发中时刻的在与它打交道&#xff0c;例如&#x…

全方位介绍工厂的MES质量检验管理系统

一、MES质量检验管理系统的定义&#xff1a; MES质量检验管理系统是基于制造执行系统的框架和功能&#xff0c;专注于产品质量的控制和管理。它通过整合和优化质量检验流程&#xff0c;提供实时的数据采集、分析和反馈&#xff0c;帮助工厂实现高效的质量管理。该系统涵盖了从…

解决高分屏DPI缩放PC端百度网盘界面模糊的问题

第一步 更新最新版本 首先&#xff0c;在百度网盘官网下载最新安装包&#xff1a; https://pan.baidu.com/download 进行覆盖安装 第二步 修改兼容性设置 右键百度网盘图标&#xff0c;点击属性&#xff0c;在兼容性选项卡中点击更改所有用户的设置 弹出的选项卡中选择更改高…

linux内核分析:虚拟化

三种虚拟化方式 1. 对于虚拟机内核来讲&#xff0c;只要将标志位设为虚拟机状态&#xff0c;我们就可以直接在 CPU 上执行大部分的指令&#xff0c;不需要虚拟化软件在中间转述&#xff0c;除非遇到特别敏感的指令&#xff0c;才需要将标志位设为物理机内核态运行&#xff0c…

【gitlab】本地项目上传gitlab

需求描述 解决方法 下面的截图是gitlab空项目的描述 上传一个本地项目按其中“Push an existing folder”命令即可。 以renren-fast项目为例 # 用git bash 下载renren-fast项目 git clone https://gitee.com/renrenio/renren-fast.git# 在renren-fast的所属目录 打开git ba…

详谈Spring

作者&#xff1a;爱塔居 专栏&#xff1a;JavaEE 目录 一、Spring是什么&#xff1f; 1.1 Spring框架的一些核心特点&#xff1a; 二、IoC&#xff08;控制反转&#xff09;是什么&#xff1f; 2.1 实现手段 2.2 依赖注入&#xff08;DI&#xff09;的实现原理 2.3 优点 三、AO…

时序分解 | Matlab实现CEEMDAN完全自适应噪声集合经验模态分解时间序列信号分解

时序分解 | Matlab实现CEEMDAN完全自适应噪声集合经验模态分解时间序列信号分解 目录 时序分解 | Matlab实现CEEMDAN完全自适应噪声集合经验模态分解时间序列信号分解效果一览基本介绍程序设计参考资料 效果一览 基本介绍 Matlab实现CEEMDAN完全自适应噪声集合经验模态分解时间…

连续爆轰发动机

0.什么是爆轰 其反应区前沿为一激波。反应区连同前驱激波称为爆轰波。爆轰波扫过后&#xff0c;反应区介质成为高温高压的爆轰产物。能够发生爆轰的系统可以是气相、液相、固相或气-液、气-固和液-固等混合相组成的系统。通常把液、固相的爆轰系统称为炸药。 19世纪80年代初&a…

子监督学习的知识点总结

监督学习 机器学习中最常见的方法是监督学习。在监督学习中&#xff0c;我们得到一组标记数据&#xff08;X&#xff0c;Y&#xff09;&#xff0c;即&#xff08;特征&#xff0c;标签&#xff09;&#xff0c;我们的任务是学习它们之间的关系。但是这种方法并不总是易于处理&…

基于微信小程序的付费自习室

博主介绍&#xff1a;✌程序员徐师兄、7年大厂程序员经历。全网粉丝30W、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ 文章目录 1 简介2 技术栈3 需求分析3.1用户需求分析3.1.1 学生用户3.1.3 管理员用户 4 数据库设计4.4.1 E…

定时器+按键控制LED流水灯模式+定时器时钟——“51单片机”

各位CSDN的uu们好呀&#xff0c;今天&#xff0c;小雅兰的内容是51单片机中的定时器以及按键控制LED流水灯模式&定时器时钟&#xff0c;下面&#xff0c;让我们进入51单片机的世界吧&#xff01;&#xff01;&#xff01; 定时器 按键控制LED流水灯模式 定时器时钟 源代…

Mac电脑BIM建模软件 Archicad 26 for Mac最新

ARCHICAD 软件特色 智能化 在2D CAD中&#xff0c;所有的建筑构件都由线条构成和表现&#xff0c;仅仅是一些线条的组合而已&#xff0c;当我们阅读图纸的时候是按照制图规范来读取这些信息。我们用一组线条表示平面中的窗&#xff0c;再用另一组不同的线条在立面中表示同一个…

C++11——神奇的右值引用与移动构造

文章目录 前言左值引用和右值引用右值引用的使用场景和意义右值引用引用左值万能引用右值引用的属性完美转发新的默认构造函数强制和禁止生成默认函数 总结 前言 本篇博客将主要讲述c11中新添的新特性——右值引用和移动构造等&#xff0c;从浅到深的了解这个新特性的用法&…

创意填充文本悬停效果

效果展示 CSS 知识点 text-shadow 属性实现 3D 文字clip-path 属性的运用 实现页面基础结构布局 <div class"container"><!-- 使用多个h2标签来实现不同颜色的3D文字 --><h2>Text</h2><h2>Text</h2><h2>Text</h2>…

好奇喵 | Tor浏览器——如何拥有一颗洋葱并使用

前言 在之前的博客中&#xff1a; 1.Surface Web —&#xff1e; Deep Web —&#xff1e; Dark Web&#xff0c;我们解释了表层网络、深层网络等的相关概念&#xff1b; 2.Tor浏览器——层层剥开洋葱&#xff0c;我们阐述了Tor的历史和基本工作原理&#xff1b; 本篇博客介…

笔记--总线舵机YB-SD15M--stm32

文章目录 前言一、官方文档的理解1.发送格式2.命令地址 二、控制文件1.c2.h 文件 前言 使用stm32控制这个总线舵机。 舵机为总线舵机。一定要配合控制板一起用&#xff0c;不然只使用stm32无法控制。 一、官方文档的理解 1.发送格式 发送格式如下&#xff0c;其中的指令类型…

2023版 STM32实战6 输出比较(PWM)包含F407/F103方式

输出比较简介和特性 -1-只有通用/高级定时器才能输出PWM -2-占空比就是高电平所占的比例 -3-输出比较就是输出不同占空比的信号 工作方式说明 -1-1- PWM工作模式 -1-2- 有效/无效电平 有效电平可以设置为高或低电平&#xff0c;是自己配置的 周期选择与计算 周期重…

成都建筑模板批发市场在哪?

成都作为中国西南地区的重要城市&#xff0c;建筑业蓬勃发展&#xff0c;建筑模板作为建筑施工的重要材料之一&#xff0c;在成都也有着广泛的需求。如果您正在寻找成都的建筑模板批发市场&#xff0c;广西贵港市能强优品木业有限公司是一家值得关注的供应商。广西贵港市能强优…

首饰饰品经营商城小程序的作用是什么

首饰如耳钉、戒指、手镯等除了高价值产品外&#xff0c;还有很多低价产品&#xff0c;市场需求客户众多&#xff0c;在实际经营中&#xff0c;商家们也会面临一些痛点。 私域话题越来越多加之线上线下同行竞争、流量匮乏等&#xff0c;更对商家选择自建商城经营平台。 通过【…

mybatise-plus的id过长问题

一、问题情景 笔者在做mp插入数据库(id已设置为自增)操作时&#xff0c;发现新增数据的id过长&#xff0c;结果导致前端JS拿到的数据出现了精度丢失问题&#xff0c;原因是后端id的类型是Long。在网上查了一下&#xff0c;只要在该属性上加上如下注解就可以 TableId(value &q…