Spring5之JdbcTemplate

news/2024/5/18 22:43:20 标签: spring, java, jdbc, 后端

Spring5 之 JdbcTemplate

  • 概念
  • 如何使用?
    • 环境搭建
      • 搭建步骤
      • 具体实现
    • 新增操作
    • 修改操作 & 删除操作
    • 查询操作(返回某个值)
    • 查询操作(返回对象)
    • 查询操作(返回集合)
    • 批量新增操作
    • 批量修改 & 批量删除

概念

  • JdbcTemplate:JdbcTemplate 是 Spring 框架对 JDBC 进行的封装,使用 JdbcTemplate 方便实现对数据库的相关操作。

如何使用?

环境搭建

搭建步骤

  1. 引入相关 jar 包
  2. 在 Spring 配置文件中配置数据库连接池
  3. 配置 JdbcTemplate 对象,注入 DataSource
  4. 创建 service 类,创建 dao 类,在 dao 类中注入 jdbcTemplate 对象

具体实现

  • 1、引入相关 jar 包

    在这里插入图片描述

  • 2、在 Spring 配置文件中配置数据库连接池

    <?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.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    ">
        <!-- 数据库连接池 -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="clone">
            <property name="url" value="jdbc:mysql:///spring_test" />
            <property name="username" value="root" />
            <property name="password" value="123456" />
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        </bean>
    </beans>
    
  • 3、配置 JdbcTemplate 对象,注入 DataSource

    <?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.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    ">
        <!-- 数据库连接池 -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="clone">
            <property name="url" value="jdbc:mysql:///spring_test" />
            <property name="username" value="root" />
            <property name="password" value="123456" />
            <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" />
        </bean>
    </beans>
    
  • 4、创建 service 和 dao 类,在 dao 类中注入 JdbcTemplate 对象

    在配置文件中开启组件扫描(也可以使用配置类代替)

    <?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.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
    ">
        <!-- 数据库连接池 -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="clone">
            <property name="url" value="jdbc:mysql:///spring_test" />
            <property name="username" value="root" />
            <property name="password" value="123456" />
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        </bean>
    
        <!-- 开启组件扫描 -->
        <context:component-scan base-package="com.laoyang.spring" />
    
        <!-- 创建 JdbcTemplate 对象 -->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <!-- 注入 dataSource -->
            <property name="dataSource" ref="dataSource" />
        </bean>
    </beans>
    

    一定要记得引入 context 名称空间

    service类

    java">package com.laoyang.spring.service;
    
    import com.laoyang.spring.dao.BookDao;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class BookService {
        /**
         * 注入 Dao
         */
        @Autowired
        private BookDao bookDao;
    }
    

    dao类(接口 & 实现类)

    java">package com.laoyang.spring.dao;
    
    public interface BookDao {
    }
    
    java">package com.laoyang.spring.dao;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class BookDaoImpl implements BookDao {
        /**
         * 注入 JdbcTemplate 对象
         */
        @Autowired
        private JdbcTemplate jdbcTemplate;
    }
    

新增操作

先提前准备好对应的数据库表t_book

在这里插入图片描述

虽然表名的意思是 “图书”,但是这里大伙可以理解为 “用户”,就当作是用户表来使用就好了,实在看不下去的可以将表名和实体类这些都改成 user

  • 1、对数据库表创建实体类

    java">package com.laoyang.spring.entity;
    
    /**
     * @ClassName Book
     * @Description: 用户类
     * @Author Laoyang
     * @Date 2021/12/20 20:04
     */
    public class Book {
        /**
         * 用户id
         */
        private String userId;
    
        /**
         * 用户名称
         */
        private String username;
    
        /**
         * 用户状态
         */
        private String ustatus;
    
        public String getUserId() {
            return userId;
        }
    
        public void setUserId(String userId) {
            this.userId = userId;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getUstatus() {
            return ustatus;
        }
    
        public void setUstatus(String ustatus) {
            this.ustatus = ustatus;
        }
    }
    
  • 2、编写 service 和 dao(在 dao 进行数据库添加操作)

    BookService 类:

    java">package com.laoyang.spring.service;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class BookService {
        /**
         * 注入 Dao
         */
        @Autowired
        private BookDao bookDao;
    
        /**
         * 新增方法
         */
        public void addUser(Book book) {
            bookDao.add(book);
        }
    }
    

    BookDao 接口:

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    
    public interface BookDao {
        /**
         * 添加用户
         * @param book
         */
        void add(Book book);
    }
    

    BookDaoImpl 类:

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class BookDaoImpl implements BookDao {
        /**
         * 注入 JdbcTemplate 对象
         */
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        /**
         * 添加用户
         * @param book
         */
        @Override
        public void add(Book book) {
            /*
             调用 jdbcTemplate 对象里面的 update(String sql, Object... args) 方法实现添加操作
             参数一:SQL 语句
             参数二:可变参数,设置 sql 中的语句值
             */
    
            // 1、创建 sql
            String sql = "insert into t_book values(?, ?, ?)";
    
            // 2、调用 update 方法实现
            Object[] books = {book.getUserId(), book.getUsername(), book.getUstatus()};
            int insert = jdbcTemplate.update(sql, books);
            // 可以将可变参数封装到数组里面在传到方法中,也可以直接将参数传到方法中
    //        int insert = jdbcTemplate.update(sql, book.getUserId(), book.getUsername(), book.getUstatus());
            if (insert > 0) {
                System.out.println("新增成功!");
                return;
            }
            System.out.println("新增失败!");
        }
    }
    
  • 3、测试效果

    java">package com.laoyang.spring.test;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import com.laoyang.spring.service.BookService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class JdbcTest {
        @Test
        public void testAddUser() {
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
    
            BookService bookService = context.getBean("bookService", BookService.class);
    
            Book book = new Book();
            book.setUserId("1001");
            book.setUsername("Tom");
            book.setUstatus("A");
            bookService.addUser(book);
        }
    }
    

    添加成功后就可以查看数据库表中的数据了

修改操作 & 删除操作

说明:因为增删改的方式都差不多,就是修改一下语句就好了,所以这里直接把修改和删除一起演示

基于上面的实体类完成这两个操作

  • 编写 service 和 dao(在 dao 进行数据库添加操作)

    BookService类

    java">package com.laoyang.spring.service;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class BookService {
        /**
         * 注入 Dao
         */
        @Autowired
        private BookDao bookDao;
    
        /**
         * 新增方法
         */
        public void addBook(Book book) {
            bookDao.add(book);
        }
    
        /**
         * 修改方法
         */
        public void updateBook(Book book) {
            bookDao.update(book);
        }
    
        /**
         * 删除方法
         */
        public void deleteBook(String userId) {
            bookDao.delete(userId);
        }
    }
    

    BookDao 接口

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    
    public interface BookDao {
        /**
         * 添加用户
         * @param book
         */
        void add(Book book);
    
        /**
         * 修改用户
         * @param book
         */
        void update(Book book);
    
        /**
         * 删除用户
         * @param userId
         */
        void delete(String userId);
    }
    

    BookDaoImpl 类

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class BookDaoImpl implements BookDao {
        /**
         * 注入 JdbcTemplate 对象
         */
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        /**
         * 添加用户
         * @param book
         */
        @Override
        public void add(Book book) {
            /*
             调用 jdbcTemplate 对象里面的 update(String sql, Object... args) 方法实现添加操作
             参数一:SQL 语句
             参数二:可变参数,设置 sql 中的语句值
             */
    
            // 1、创建 sql
            String sql = "insert into t_book values(?, ?, ?)";
    
            // 2、调用 update 方法实现
            Object[] books = {book.getUserId(), book.getUsername(), book.getUstatus()};
            int insert = jdbcTemplate.update(sql, books);
            // 可以将可变参数封装到数组里面在传到方法中,也可以直接将参数传到方法中
    //        int insert = jdbcTemplate.update(sql, book.getUserId(), book.getUsername(), book.getUstatus());
            if (insert > 0) {
                System.out.println("新增成功!");
                return;
            }
            System.out.println("新增失败!");
        }
    
        /**
         * 修改用户
         * @param book
         */
        @Override
        public void update(Book book) {
            String sql = "update t_book set username=?, ustatus=? where user_id=?";
            Object[] books = {book.getUsername(), book.getUstatus(), book.getUserId()};
            int update = jdbcTemplate.update(sql, books);
            if (update > 0) {
                System.out.println("修改成功!");
                return;
            }
            System.out.println("修改失败!");
        }
    
        /**
         * 删除用户
         * @param userId
         */
        @Override
        public void delete(String userId) {
            String sql = "delete from t_book where user_id = ?";
            int delet = jdbcTemplate.update(sql, userId);
            if (delet > 0) {
                System.out.println("删除成功!");
                return;
            }
            System.out.println("删除失败!");
        }
    }
    
  • 测试效果

    java">package com.laoyang.spring.test;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import com.laoyang.spring.service.BookService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class JdbcTest {
    	// 修改操作
        @Test
        public void testUpdateUser() {
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
    
            BookService bookService = context.getBean("bookService", BookService.class);
    
            Book book = new Book();
            book.setUserId("1001");
            book.setUsername("Jerry");
            book.setUstatus("C");
            bookService.updateBook(book);
        }
    
    	// 删除操作
        @Test
        public void testDeleteUser() {
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
    
            BookService bookService = context.getBean("bookService", BookService.class);
            bookService.deleteBook("1001");
        }
    }
    

查询操作(返回某个值)

案例:查询表中有多少个用户,返回的是某个值

  • 编写 service 和 dao(在 dao 进行数据库添加操作)
    BookService 类

    java">package com.laoyang.spring.service;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class BookService {
        /**
         * 注入 Dao
         */
        @Autowired
        private BookDao bookDao;
        
        /**
         * 查询表中的用户总数
         */
        public int findCount() {
            return bookDao.selectCount();
        }
    }
    

    BookDao 接口

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    
    public interface BookDao {
        /**
         * 查询表中的用户总数
         */
        int selectCount();
    }
    

    BookDaoImpl 类

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class BookDaoImpl implements BookDao {
        /**
         * 注入 JdbcTemplate 对象
         */
        @Autowired
        private JdbcTemplate jdbcTemplate;
        
        /**
         * 查询表中的用户总数
         */
        @Override
        public int selectCount() {
            /*
            调用 jdbcTemplate 对象里面的 queryForObject(String sql, Class<T> requiredType) 方法实现该操作
            参数一:sql 语句
            参数二:返回类型的 Class
             */
    
            String sql = "select count(user_id) from t_book";
            Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
            return count;
        }
    }
    
  • 测试效果

    java">package com.laoyang.spring.test;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import com.laoyang.spring.service.BookService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class JdbcTest {
        @Test
        public void testCount() {
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
    
            BookService bookService = context.getBean("bookService", BookService.class);
            int count = bookService.findCount();
            System.out.println("当前表中还有" + count + "个用户。");
        }
    }
    

查询操作(返回对象)

案例:查询 id 为 1001 的用户详情

  • 因为需要查看对象数据,所以我们先给 Book 实体类编写一个 toString 方法

    java">package com.laoyang.spring.entity;
    
    /**
     * @ClassName Book
     * @Description: 用户类
     * @Author Laoyang
     * @Date 2021/12/20 20:04
     */
    public class Book {
        //...此处为了简便省略前面的配置
    
        @Override
        public String toString() {
            return "Book{" +
                    "userId='" + userId + '\'' +
                    ", username='" + username + '\'' +
                    ", ustatus='" + ustatus + '\'' +
                    '}';
        }
    }
    
  • 编写 service 和 dao(在 dao 进行数据库添加操作)
    BookService 类

    java">package com.laoyang.spring.service;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class BookService {
        /**
         * 注入 Dao
         */
        @Autowired
        private BookDao bookDao;
        
        /**
         * 查询 id 为 1001 的用户详情
         */
        public Book findBookByUserId(String userId) {
            return bookDao.findBookByUserId(userId);
        }
    }
    

    BookDao 接口

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    
    public interface BookDao {
        /**
         * 查询 id 为 1001 的用户详情
         */
        Book findBookByUserId(String userId);
    }
    

    BookDaoImpl 类

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public class BookDaoImpl implements BookDao {
        /**
         * 查询 id 为 1001 的用户详情
         */
        @Override
        public Book findBookByUserId(String userId) {
            /*
            调用 jdbcTemplate 对象里面的 queryForObject(String sql, RowMapper<T> rowMapper, Object... args) 方法实现该操作
            参数一:sql 语句
            参数二:rowMapper 是一个接口,针对返回不同类型的数据,使用这个接口里面的实现类完成数据封装
            参数三:可变参数
             */
            String sql = "select user_id, username, ustatus from t_book where user_id=?";
            Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), userId);
            if (book != null) {
                return book;
            }
            return null;
        }
    }
    
  • 测试效果

    java">package com.laoyang.spring.test;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import com.laoyang.spring.service.BookService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class JdbcTest {
        @Test
        public void testBook() {
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
    
            BookService bookService = context.getBean("bookService", BookService.class);
            Book book = bookService.findBookByUserId("1001");
            System.out.println(book);
        }
    }
    

查询操作(返回集合)

案例:查询所有用户信息

  • 编写 service 和 dao(在 dao 进行数据库添加操作)
    BookService 类

    java">package com.laoyang.spring.service;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.List;
    
    @Service
    public class BookService {
        /**
         * 注入 Dao
         */
        @Autowired
        private BookDao bookDao;
        
        /**
         * 查询所有用户信息
         */
        public List<Book> findBookByAll() {
            return bookDao.findBookByAll();
        }
    }
    

    BookDao 接口

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import java.util.List;
    
    public interface BookDao {
        /**
         * 查询所有用户信息
         */
        List<Book> findBookByAll();
    }
    

    BookDaoImpl 类

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    import java.util.ArrayList;
    import java.util.List;
    
    @Repository
    public class BookDaoImpl implements BookDao {
        /**
         * 注入 JdbcTemplate 对象
         */
        @Autowired
        private JdbcTemplate jdbcTemplate;
        
        /**
         * 查询所有用户信息
         */
        @Override
        public List<Book> findBookByAll() {
            /*
            调用 jdbcTemplate 对象里面的 query(String sql, RowMapper<T> rowMapper, Object... args) 方法实现该操作
            参数一:sql 语句
            参数二:rowMapper 是一个接口,针对返回不同类型的数据,使用这个接口里面的实现类完成数据封装
            参数三:可变参数,可选
             */
            String sql = "select user_id, username, ustatus from t_book";
            List<Book> books = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
            if (!books.isEmpty()) {
                return books;
            }
            return null;
        }
    }
    
  • 测试效果

    java">package com.laoyang.spring.test;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import com.laoyang.spring.service.BookService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import java.util.Arrays;
    import java.util.List;
    
    public class JdbcTest {
        @Test
        public void testBookAll() {
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
    
            BookService bookService = context.getBean("bookService", BookService.class);
            List<Book> books = bookService.findBookByAll();
            System.out.println(books);
        }
    }
    

批量新增操作

批量操作:操作表里面的多条记录

  • 编写 service 和 dao(在 dao 进行数据库添加操作)
    BookService 类

    java">package com.laoyang.spring.service;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.List;
    
    @Service
    public class BookService {
        /**
         * 注入 Dao
         */
        @Autowired
        private BookDao bookDao;
        
        /**
         * 批量新增用户
         */
        public void addBooksInBulk(List<Object[]> books) {
            bookDao.addBooksInBulk(books);
        }
    }
    

    BookDao 接口

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import java.util.List;
    
    public interface BookDao {
        /**
         * 批量新增用户
         * @param books
         */
        void addBooksInBulk(List<Object[]> books);
    }
    

    BookDaoImpl 类

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    import java.util.ArrayList;
    import java.util.List;
    
    @Repository
    public class BookDaoImpl implements BookDao {
        /**
         * 注入 JdbcTemplate 对象
         */
        @Autowired
        private JdbcTemplate jdbcTemplate;
        
        /**
         * 批量新增用户
         * @param books
         */
        @Override
        public void addBooksInBulk(List<Object[]> books) {
            /*
            调用 jdbcTemplate 对象里面的 batchUpdate(String sql, List<Object[]> batchArgs) 方法实现该操作
            参数一:sql语句
            参数二:List集合,添加多条的数据
             */
            String sql = "insert into t_book values(?, ?, ?)";
            int[] adds = jdbcTemplate.batchUpdate(sql, books);
            if (adds != null && adds.length > 0) {
                System.out.println("批量添加成功!");
                return;
            }
            System.out.println("批量添加失败!");
        }
    }
    
  • 测试效果

    java">package com.laoyang.spring.test;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import com.laoyang.spring.service.BookService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class JdbcTest {
        @Test
        public void testAddBooks() {
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
            BookService bookService = context.getBean("bookService", BookService.class);
    
            List<Object[]> bookList = new ArrayList<>();
            Object[] bookArray1 = {"1003", "Mel", "C"};
            Object[] bookArray2 = {"1004", "Jack", "B"};
            bookList.add(bookArray1);
            bookList.add(bookArray2);
    
            bookService.addBooksInBulk(bookList);
        }
    }
    

批量修改 & 批量删除

  • 编写 service 和 dao(在 dao 进行数据库添加操作)
    BookService 类

    java">package com.laoyang.spring.service;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.List;
    
    @Service
    public class BookService {
        /**
         * 注入 Dao
         */
        @Autowired
        private BookDao bookDao;
        
        /**
         * 批量修改用户
         */
        public void updateBooksInBulk(List<Object[]> books) {
            bookDao.updateBooksInBulk(books);
        }
    
        /**
         * 批量删除用户
         */
        public void deleteBooksInBulk(List<Object[]> userIds) {
            bookDao.deleteBooksInBulk(userIds);
        }
    }
    

    BookDao 接口

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import java.util.List;
    
    public interface BookDao {
        /**
         * 批量修改用户
         */
        void updateBooksInBulk(List<Object[]> books);
    
        /**
         * 批量删除用户
         */
        void deleteBooksInBulk(List<Object[]> userIds);
    }
    

    BookDaoImpl 类

    java">package com.laoyang.spring.dao;
    
    import com.laoyang.spring.entity.Book;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    import java.util.ArrayList;
    import java.util.List;
    
    @Repository
    public class BookDaoImpl implements BookDao {
        /**
         * 注入 JdbcTemplate 对象
         */
        @Autowired
        private JdbcTemplate jdbcTemplate;
        
        /**
         * 批量修改用户
         */
        @Override
        public void updateBooksInBulk(List<Object[]> books) {
            String sql = "update t_book set username = ?, ustatus = ? where user_id = ?";
            int[] updates = jdbcTemplate.batchUpdate(sql, books);
            if (updates != null && updates.length > 0) {
                System.out.println("批量修改成功!");
                return;
            }
            System.out.println("批量修改失败!");
        }
    
        /**
         * 批量删除用户
         */
        @Override
        public void deleteBooksInBulk(List<Object[]> userIds) {
            String sql = "delete from t_book where user_id = ?";
            int[] deletes = jdbcTemplate.batchUpdate(sql, userIds);
            if (deletes != null && deletes.length > 0) {
                System.out.println("批量删除成功!");
                return;
            }
            System.out.println("批量删除失败!");
        }
    }
    
  • 测试效果

    java">package com.laoyang.spring.test;
    
    import com.laoyang.spring.dao.BookDao;
    import com.laoyang.spring.entity.Book;
    import com.laoyang.spring.service.BookService;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class JdbcTest {
        @Test
        public void testUpdateBooks() {
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
            BookService bookService = context.getBean("bookService", BookService.class);
    
            List<Object[]> bookList = new ArrayList<>();
            Object[] bookArray1 = {"Ronaldinho", "A", "1003"};
            Object[] bookArray2 = {"lamb", "A", "1004"};
            bookList.add(bookArray1);
            bookList.add(bookArray2);
    
            bookService.updateBooksInBulk(bookList);
        }
    
        @Test
        public void testDeleteBooks() {
            ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
            BookService bookService = context.getBean("bookService", BookService.class);
    
            List<Object[]> bookList = new ArrayList<>();
            Object[] bookArray1 = {"1003"};
            Object[] bookArray2 = {"1004"};
            bookList.add(bookArray1);
            bookList.add(bookArray2);
    
            bookService.deleteBooksInBulk(bookList);
        }
    }
    

http://www.niftyadmin.cn/n/1268817.html

相关文章

Leetcode 33:搜索旋转排列数组(最详细的解法!!!)

假设按照升序排序的数组在预先未知的某个点上进行了旋转。 ( 例如&#xff0c;数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。 搜索一个给定的目标值&#xff0c;如果数组中存在这个目标值&#xff0c;则返回它的索引&#xff0c;否则返回 -1 。 你可以假设数组中不存在…

Spring5事务管理

Spring5事务管理事务概念复习什么是事务&#xff1f;事务四大特性&#xff08;ACID&#xff09;搭建事务操作环境一、创建数据库表&#xff08;t_account&#xff09;&#xff0c;添加记录二、创建 service&#xff0c;搭建 dao&#xff0c;完成对象创建和注入关系三、在 dao 和…

Leetcode 34:在排序数组中查找元素的第一个位置和最后一个位置(最详细的解法!!!)

给定一个按照升序排列的整数数组 nums&#xff0c;和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 你的算法时间复杂度必须是 O(log n) 级别。 如果数组中不存在目标值&#xff0c;返回 [-1, -1]。 示例 1: 输入: nums [5,7,7,8,8,10], target 8 输…

Spring5新功能

Spring5 新功能新功能概述Spring5 整合日志框架实现步骤Spring5 自带的日志功能Spring 5 框架的核心容器支持 Nullable 注解Spring5 核心容器支持函数式风格 GenericApplicationContext/AnnotationConfigApplicationContextGenericApplicationContextAnnotationConfigApplicati…

Leetcode 48:旋转图像(最详细的解法!!!)

给定一个 n n 的二维矩阵表示一个图像。 将图像顺时针旋转 90 度。 说明&#xff1a; 你必须在原地旋转图像&#xff0c;这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。 示例 1: 给定 matrix [[1,2,3],[4,5,6],[7,8,9] ],原地旋转输入矩阵&a…

Leetcode 926:将字符串翻转到单调递增(最详细的解法!!!)

如果一个由 0 和 1 组成的字符串&#xff0c;是以一些 0&#xff08;可能没有 0&#xff09;后面跟着一些 1&#xff08;也可能没有 1&#xff09;的形式组成的&#xff0c;那么该字符串是单调递增的。 我们给出一个由字符 0 和 1 组成的字符串 S&#xff0c;我们可以将任何 0…

IDEA 配置 Tomcat

前言 这里以 Tomcat 8 为例 一、下载 Tomcat 官网&#xff1a;https://tomcat.apache.org/ 下载可能会稍微有点慢 二、在 IDEA 中配置 Tomcat 点击 Edit 选择 Tomcat Server 》 Loval&#xff08;下面有一个差不多的 TomEE&#xff0c;但是不要选错了&#xff0c;这里是选…

Leetcode 925:长按键入(最详细的解法!!!)

你的朋友正在使用键盘输入他的名字 name。偶尔&#xff0c;在键入字符 c 时&#xff0c;按键可能会被长按&#xff0c;而字符可能被输入 1 次或多次。 你将会检查键盘输入的字符 typed。如果它对应的可能是你的朋友的名字&#xff08;其中一些字符可能被长按&#xff09;&…