Spring5入门到实战------13、使用JdbcTemplate操作数据库(批量增删改)。具体代码+讲解 【下篇】

简介: 这篇文章是Spring5框架的实战教程,深入讲解了如何使用JdbcTemplate进行数据库的批量操作,包括批量添加、批量修改和批量删除的具体代码实现和测试过程,并通过完整的项目案例展示了如何在实际开发中应用这些技术。

Spring5入门到实战------12、使用JdbcTemplate操作数据库(增删改查)。具体代码+讲解 【上篇】

这一篇主要介绍批量操作数据库

1、jdbcTemplate 实现批量添加操作

在这里插入图片描述
有两个参数
第一个参数:sql 语句
第二个参数:List 集合,添加多条记录数据

核心

    @Override
    public void batchAdd(List<Object[]> batchArgs) {
        String sql = "insert into t_book values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql,batchArgs);
        System.out.println(Arrays.toString(ints));
    }

测试

    @Test
    public void testJdbcTemplate4(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 ={3,"C语言","出售"};
        Object[] o2 ={4,"Python语言","出售"};
        Object[] o3 ={5,"Php语言","出售"};
        batchArgs.add(o1);
        batchArgs.add(o2);
        batchArgs.add(o3);
        bookService.batchAdd(batchArgs);

    }

测试结果

在这里插入图片描述

2、JdbcTemplate 实现批量修改操作

核心

   @Override
    public void batchUpdate(List<Object[]> batchArgs) {
        String sql = "update t_book set book_name=?,isSale=? where book_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql,batchArgs);
        System.out.println(Arrays.toString(ints));
    }

测试

    @Test
    public void testJdbcTemplate5(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 ={"C语言001","出售",3};
        Object[] o2 ={"Python语言001","出售",4};
        Object[] o3 ={"Php语言001","出售",5};
        batchArgs.add(o1);
        batchArgs.add(o2);
        batchArgs.add(o3);
        bookService.batchUpdate(batchArgs);

    }

测试结果

在这里插入图片描述

3、JdbcTemplate 实现批量删除操作

核心部分

   @Override
    public void batchDelete(List<Object[]> batchArgs) {
        String sql = "delete from t_book where book_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql,batchArgs);
        System.out.println(Arrays.toString(ints));
    }

测试

    @Test
    public void testJdbcTemplate6(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 ={3};
        Object[] o2 ={5};
        batchArgs.add(o1);
        batchArgs.add(o2);
        bookService.batchDelete(batchArgs);

    }

测试结果
在这里插入图片描述

4、完整的项目案例

4.1 目录结构

在这里插入图片描述

4.2 BookDao.java

/**
 * @author Lenovo
 * @version 1.0
 * @data 2022/10/23 15:53
 */
public interface BookDao {

    /**
     * 批量添加
     * @param batchArgs
     * @return
     */
    void batchAdd(List<Object[]> batchArgs);

    /**
     * 批量修改
     * @param batchArgs
     * @return
     */
    void batchUpdate(List<Object[]> batchArgs);

    /**
     * 批量删除
     * @param batchArgs
     * @return
     */
    void batchDelete(List<Object[]> batchArgs);

}

4.3 BookDaoImpl.java

/**
 * @author Lenovo
 * @version 1.0
 * @data 2022/10/23 15:53
 */
@Repository
public class BookDaoImpl implements BookDao{

    /**
     * 注入jdbcTemplate
     */
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void batchAdd(List<Object[]> batchArgs) {
        String sql = "insert into t_book values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql,batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchUpdate(List<Object[]> batchArgs) {
        String sql = "update t_book set book_name=?,isSale=? where book_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql,batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    @Override
    public void batchDelete(List<Object[]> batchArgs) {
        String sql = "delete from t_book where book_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql,batchArgs);
        System.out.println(Arrays.toString(ints));
    }
}

4.4 BookService.java

/**
 * @author Lenovo
 * @version 1.0
 * @data 2022/10/23 15:53
 */
@Service
public class BookService {
    /**
     * 注入dao
     */
    @Autowired
    private BookDao bookDao;


    /**
     * 批量添加
     * @return
     */
    public void batchAdd(List<Object[]> batchArgs){
       bookDao.batchAdd(batchArgs);
    }

    /**
     * 批量修改
     * @return
     */
    public void batchUpdate(List<Object[]> batchArgs){
        bookDao.batchUpdate(batchArgs);
    }


    /**
     * 批量删除
     * @return
     */
    public void batchDelete(List<Object[]> batchArgs){
        bookDao.batchDelete(batchArgs);
    }

}

4.5 bean.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"
       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.zyz"></context:component-scan>
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3306/user_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>

    <!--jdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

4.6 TestDemo.java

/**
 * @author Lenovo
 * @version 1.0
 * @data 2022/10/23 16:26
 */
public class TestDemo {

    @Test
    public void testJdbcTemplate4(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 ={3,"C语言","出售"};
        Object[] o2 ={4,"Python语言","出售"};
        Object[] o3 ={5,"Php语言","出售"};
        batchArgs.add(o1);
        batchArgs.add(o2);
        batchArgs.add(o3);
        bookService.batchAdd(batchArgs);

    }

    @Test
    public void testJdbcTemplate5(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 ={"C语言001","出售",3};
        Object[] o2 ={"Python语言001","出售",4};
        Object[] o3 ={"Php语言001","出售",5};
        batchArgs.add(o1);
        batchArgs.add(o2);
        batchArgs.add(o3);
        bookService.batchUpdate(batchArgs);

    }

    @Test
    public void testJdbcTemplate6(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 ={3};
        Object[] o2 ={5};
        batchArgs.add(o1);
        batchArgs.add(o2);
        bookService.batchDelete(batchArgs);

    }
}

4.7 Book.java

可以使用lombok插件、简化get/set

/**
 * @author Lenovo
 * @version 1.0
 * @data 2022/10/23 16:10
 */
public class Book {
    private int book_id;
    private String book_name;
    private String isSale;

    public int getBook_id() {
        return book_id;
    }

    public void setBook_id(int book_id) {
        this.book_id = book_id;
    }

    public String getBook_name() {
        return book_name;
    }

    public void setBook_name(String book_name) {
        this.book_name = book_name;
    }

    public String getIsSale() {
        return isSale;
    }

    public void setIsSale(String isSale) {
        this.isSale = isSale;
    }

    @Override
    public String toString() {
        return "Book{" +
                "book_id=" + book_id +
                ", book_name='" + book_name + '\'' +
                ", isSale='" + isSale + '\'' +
                '}';
    }
}

5、后语

主要用的时候、要知道使用哪个方法就行。学无止境。。。。。。

相关文章
|
9天前
|
SQL NoSQL Java
彻底革新你的数据库操作体验!Micronaut数据访问技巧让你瞬间爱上代码编写!
【9月更文挑战第10天】Java开发者们一直在寻找简化应用程序与数据库交互的方法。Micronaut作为一个现代框架,提供了多种工具和特性来提升数据访问效率。本文介绍如何使用Micronaut简化数据库操作,并提供具体示例代码。Micronaut支持JPA/Hibernate、SQL及NoSQL(如MongoDB),简化配置并无缝集成。通过定义带有`@Repository`注解的接口,可以实现Spring Data风格的命名查询。
25 6
|
11天前
|
前端开发 数据库
数据库表设计生成代码
BizWorks ToolKit插件集成Mybatis-Plus代码生成工具,支持从数据库表生成代码,便于研发过程中数据模型变更后的代码同步。本文介绍批量生成代码的方法、配置说明及项目示例。配置文件`*.mp.yaml`用于描述生成行为,可放置于`src/main/resource/bizworks/mybatis-plus/`路径下。配置包括数据库信息、输出目录及包名等。通过IDEA右键菜单即可启动代码生成。具体配置和示例详见文档。
21 2
|
12天前
|
前端开发 数据库 开发者
数据模型(数据库表设计)生成代码
BizWorks ToolKit 插件集成 Mybatis-Plus 代码生成工具,支持从数据库表批量生成代码,简化开发流程。本文详细介绍配置方法及项目示例,包括配置文件格式、生成选项及具体操作步骤,帮助开发者快速实现代码同步更新。配置文件 `.mp.yaml` 支持自定义输出目录、生成组件等,适用于多种项目结构。
25 0
|
12天前
|
关系型数据库 数据库 网络虚拟化
Docker环境下重启PostgreSQL数据库服务的全面指南与代码示例
由于时间和空间限制,我将在后续的回答中分别涉及到“Python中采用lasso、SCAD、LARS技术分析棒球运动员薪资的案例集锦”以及“Docker环境下重启PostgreSQL数据库服务的全面指南与代码示例”。如果你有任何一个问题的优先顺序或需要立即回答的,请告知。
21 0
|
16天前
|
SQL 安全 数据库
基于SQL Server事务日志的数据库恢复技术及实战代码详解
基于事务日志的数据库恢复技术是SQL Server中一个非常强大的功能,它能够帮助数据库管理员在数据丢失或损坏的情况下,有效地恢复数据。通过定期备份数据库和事务日志,并在需要时按照正确的步骤恢复,可以最大限度地减少数据丢失的风险。需要注意的是,恢复数据是一个需要谨慎操作的过程,建议在执行恢复操作之前,详细了解相关的操作步骤和注意事项,以确保数据的安全和完整。
32 0
|
19天前
|
JSON 数据格式 Java
化繁为简的魔法:Struts 2 与 JSON 联手打造超流畅数据交换体验,让应用飞起来!
【8月更文挑战第31天】在现代 Web 开发中,JSON 成为数据交换的主流格式,以其轻量、易读和易解析的特点受到青睐。Struts 2 内置对 JSON 的支持,结合 Jackson 库可便捷实现数据传输。本文通过具体示例展示了如何在 Struts 2 中进行 JSON 数据的序列化与反序列化,并结合 AJAX 技术提升 Web 应用的响应速度和用户体验。
46 0
|
19天前
|
开发者 前端开发 JavaScript
如何解锁Play Framework的模块化力量?揭秘构建未来Web应用的关键策略
【8月更文挑战第31天】在现代软件开发中,模块化设计对于构建可维护和可扩展的应用程序至关重要。Play Framework作为一个高性能Web应用框架,提供了强大的模块化支持,使开发者能够将应用分解为独立且可重用的模块。本文将探讨Play Framework中模块化设计的最佳实践,并通过示例代码展示如何创建模块、使用依赖注入管理模块依赖、模块化前端资源及测试模块,帮助开发者构建结构清晰、易于维护和扩展的应用程序。
27 0
|
19天前
|
数据库 Java 数据库连接
玩转Play Framework的秘密武器:Ebean ORM带你解锁高效数据库操作新姿势,让你的代码从此飞起来!
【8月更文挑战第31天】Play Framework 以其简洁的 API 和高效开发体验著称,Ebean ORM 则是其推荐的对象关系映射(ORM)工具之一。Ebean 可将 Java 对象轻松映射到数据库表,简化数据库交互。本文将指导你在 Play Framework 中使用 Ebean ORM 进行数据库操作,涵盖项目创建、依赖引入、数据库配置、模型定义及 CRUD 操作,并通过示例代码展示实现过程。通过这些步骤,你将学会如何利用 Ebean 的丰富功能,如事务管理、查询构建等,提升 Web 应用的数据库交互能力。
26 0
|
19天前
|
数据库 开发者
从EF6无缝切换到Entity Framework Core:一份详尽无遗的开发者实战攻略,带你领略数据库操作的全新境界,让代码优雅转身,性能与可维护性双丰收的秘密武器
【8月更文挑战第31天】本文通过详细的代码示例,介绍了如何将基于 EF6 的应用程序平滑迁移到 EF Core。从创建初始 EF6 项目并定义数据库上下文开始,逐步演示了如何使用 EF6 进行数据操作。随后,文章详细讲解了迁移到 EF Core 的步骤,包括配置 EF Core 数据库上下文、定义领域模型及数据操作等。通过具体示例,展示了 EF Core 的强大功能,帮助开发者构建高效且可扩展的数据访问层。
23 0
|
存储 缓存 前端开发
spring中这些能升华代码的技巧,可能会让你爱不释手(下)
spring中这些能升华代码的技巧,可能会让你爱不释手
spring中这些能升华代码的技巧,可能会让你爱不释手(下)