【Spring5】JdbcTemplate

什么是 JdbcTemplate

【Spring5】JdbcTemplate_第1张图片


Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 更加方便实现对数据库操作

配置工作

引入jar包

【Spring5】JdbcTemplate_第2张图片

配置xml文件

在 spring 配置文件配置数据库连接池
druidbean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/beans/spring-context.xsd">

    <!--直接配置连接池-->
    <!--<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        &lt;!&ndash; 获取properties文件内容,根据key获取,使用spring表达式获取 &ndash;&gt;
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>-->

    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 获取properties文件内容,根据key获取,使用spring表达式获取 -->
        <property name="driverClassName" value="${prop.driverClass}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.username}"></property>
        <property name="password" value="${prop.password}"></property>
    </bean>
</beans>

jdbc.properties

prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3308/springdb
prop.username=root
prop.password=

(3)配置 JdbcTemplate 对象,注入 DataSource


<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="dataSource">property>
bean>

(4)创建 service 类,创建 dao 类,在 dao 注入 jdbcTemplate 对象

  • 配置文件

    
    <context:component-scan base-package="com.atguigu">context:component-scan>
    

    ⚫ Service
    在服务层执行Dao层的方法

    @Service
    public class BookService {
    	//注入 dao
    	@Autowired
    	private BookDao bookDao;
    }
    

    ⚫ Dao

    @Repository
    public class BookDaoImpl implements BookDao {
    	//注入 JdbcTemplate
    	@Autowired
    	private JdbcTemplate jdbcTemplate;
    }
    

    创建数据库对应实体类Book

    package com.amhu.yx.spring.dao;
    
    public class Book {
        private String bookId;
        private String bookName;
        private String bookStatus;
    
        public void setBookId(String bookId) {
            this.bookId = bookId;
        }
    
        public void setBookName(String bookName) {
            this.bookName = bookName;
        }
    
        public void setBookStatus(String bookStatus) {
            this.bookStatus = bookStatus;
        }
    
        public String getBookId() {
            return bookId;
        }
    
        public String getBookName() {
            return bookName;
        }
    
        public String getBookStatus() {
            return bookStatus;
        }
    }
    

添加数据

编写 dao和 service

BookDao接口中添加insert()方法,

public interface BookDao {
    public void insert(Book book);
}

BookDaoImpl中添加insert方法具体逻辑

调用 JdbcTemplate 对象里面 update 方法实现添加操作

update (String sql, Object[] args)
  • 有两个参数
  • 第一个参数:sql 语句
  • 第二个参数:可变参数,设置 sql 语句值
    @Repository
    public class BookDaoImpl implements BookDao {
        
        //注入JDBCTemplate
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        //向数据库中添加数据的方法
        @Override
        public void insert(Book book) {
            //1.添加数据的sql语句
            String sql = "insert into t_book vlaues(?,?,?)";
            //2.调用方法实现
            Object[] args = {book.getBookId(), book.getBookName(), book.getBookStatus()};
            //3.执行sql语句,并返回改变表中数据的行数
            int update = jdbcTemplate.update(sql, args);
            System.out.println(update);
        }
    }
    
    BookService中通过BookDao对象调用insert方法
    @Service
    public class BookService {
    
        //注入dao
        @Autowired
        private BookDao bookDao;
    
        //添加方法
        public void insertBook(Book book){
            bookDao.insert(book);
        }
    }
    

测试代码:

public class TestJdbcTemplate {
    @Test
    public void testJdbcTemplate(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("druidbean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        Book book = new Book();
        book.setBookId("1");
        book.setBookName("Java编程思想");
        book.setBookStatus("阅读中");
        bookService.insertBook(book);
    }
}    

修改和删除

1、修改
@Override
public void updateBook(Book book) {
String sql = "update t_book set username=?,ustatus=? where user_id=?";
Object[] args = {book.getUsername(), book.getUstatus(),book.getUserId()};
int update = jdbcTemplate.update(sql, args);
System.out.println(update);
}
2、删除
@Override
public void delete(String id) {
String sql = "delete from t_book where user_id=?";
int update = jdbcTemplate.update(sql, id);
System.out.println(update);
}

查询数据

结果返回一个值

queryForObject(String sql, Class<T> requiredType)

String sql : sql查询语句
Class requiredType : 返回类型Class

我门可以通过如下代码查询表中有多少条记录,结果返回一个数字:

//查询表记录数
@Override
public int selectCount() {
	String sql = "select count(*) from t_book";
	Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
	return count;
}

结果返回一个对象

queryForObject(String sql, RowMapper<T> rowMapper, Object... args)
  • 第一个参数:sql 语句
  • 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成
    数据封装
  • 第三个参数:sql 语句值

可以通过下面的代码查询一本书的详细信息,查询结果返回一个book对象

//查询返回对象
@Override
public Book findBookInfo(String id) {
	String sql = "select * from t_book where user_id=?";
	//调用方法
	Book book = jdbcTemplate.queryForObject(sql, new
	BeanPropertyRowMapper<Book>(Book.class), id);
	return book;
}

结果返回一个集合

query(String sql, RowMapper<T> rowMapper, Object... args)
  • 第一个参数:sql 语句
  • 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成
    数据封装
  • 第三个参数:sql 语句值

可以通过下面的代码查询图书列表分页,结果返回一个集合

//查询返回集合
@Override
public List<Book> findAllBook() {
	String sql = "select * from t_book";
	//调用方法
	List<Book> bookList = jdbcTemplate.query(sql, new
	BeanPropertyRowMapper<Book>(Book.class));
	return bookList;
}

批量操作数据

1、批量操作:操作表里面多条记录
2、JdbcTemplate 实现批量添加操作
⚫ 有两个参数
⚫ 第一个参数:sql 语句
⚫ 第二个参数:List 集合,添加多条记录数据

//批量添加
@Override
public void batchAddBook(List<Object[]> batchArgs) {
	String sql = "insert into t_book values(?,?,?)";
	int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
	System.out.println(Arrays.toString(ints));
}
//批量添加测试
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3","java","a"};
Object[] o2 = {"4","c++","b"};
Object[] o3 = {"5","MySQL","c"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用批量添加
bookService.batchAdd(batchArgs);

3、JdbcTemplate 实现批量修改操作
注意,修改时

Object[] o1 = {"java0909","a3","3"};
Object[] o2 = {"c++1010","b4","4"};
Object[] o3 = {"MySQL1111","c5","5"};

中元素顺序要与sql语句代码元素顺序相同:update t_book set bookname=?,bookstatus=? where bookid=?

//批量修改
@Override
public void batchUpdateBook(List<Object[]> batchArgs) {
	String sql = "update t_book set username=?,ustatus=? where user_id=?";
	int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
	System.out.println(Arrays.toString(ints));
}
//批量修改
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"java0909","a3","3"};
Object[] o2 = {"c++1010","b4","4"};
Object[] o3 = {"MySQL1111","c5","5"};
batchArgs.add(o1);
batchArgs.add(o2);
batchArgs.add(o3);
//调用方法实现批量修改
bookService.batchUpdate(batchArgs);

4、JdbcTemplate 实现批量删除操作

//批量删除
@Override
public void batchDeleteBook(List<Object[]> batchArgs) {
	String sql = "delete from t_book where user_id=?";
	int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
	System.out.println(Arrays.toString(ints));
}
//批量删除
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3"};
Object[] o2 = {"4"};
batchArgs.add(o1);
batchArgs.add(o2);
//调用方法实现批量删除
bookService.batchDelete(batchArgs);

完整代码:
先来分析一下,
首先在dao层定义一个接口,里面规范了各种方法,然后定义一个实现类实现该接口,完善代码(JdbcTemplate)。
在service层定义一个实现类的对象,调用实现类的方法。
需要操作数据库时,只需要操作service层的对象就可以了。

druidbean.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       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.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:component-scan base-package="com.amhu.yx.spring">context:component-scan>

    
    

    
    

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:3308/springdb" />
        <property name="username" value="root" />
        <property name="password" value="" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    bean>

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

beans>

BookDao.java

package com.amhu.yx.spring.dao;

import java.util.List;

public interface BookDao {
    public void insert(Book book);
    public void update(Book book);
    public void delete(String id);
    public int selectCount();//查询数据库表中有多少条数据
    public Book queryBookInfo(String id);//根据书的id查询一本书的信息
    public List<Book> queryBookPage();//查询一页图书

    public void batchAddBook(List<Object[]> batchArgs);//批量添加数据
    public void batchUpdateBook(List<Object[]> batchArgs);
    public void batchDeleteBook(List<Object[]> batchArgs);
}

BookDaoImpl.java

package com.amhu.yx.spring.dao;

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.Arrays;
import java.util.List;

@Repository
public class BookDaoImpl implements BookDao {

    //注入JDBCTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //向数据库中添加数据的方法
    @Override
    public void insert(Book book) {
        //1.添加数据的sql语句
        String sql = "insert into t_book values(?,?,?)";
        //2.调用方法实现
        Object[] args = {book.getBookId(), book.getBookName(), book.getBookStatus()};
        //3.执行sql语句,并返回改变表中数据的行数
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }


    //修改数据库中数据
    @Override
    public void update(Book book) {
        String sql = "update t_book set bookid=?, bookname=?, bookstatus=?";
        Object[] args = {book.getBookId(), book.getBookName(), book.getBookStatus()};
        int update =jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    //删除数据库中数据
    @Override
    public void delete(String id) {
        String sql = "delete from t_book where bookid=?";
        int update =jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

    //统计数据条数
    @Override
    public int selectCount() {
        String sql = "select count(*) from t_book";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    //根据id来查询信息
    @Override
    public Book queryBookInfo(String id) {
        String sql = "select * from t_book where bookid=?";
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class),id);
        return book;
    }

    //一次查询一页数据
    @Override
    public List<Book> queryBookPage() {
        String sql = "select * from t_book";
        List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        return bookList;
    }

    //批量添加数据
    @Override
    public void batchAddBook(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 batchUpdateBook(List<Object[]> batchArgs) {
        String sql = "update t_book set bookname=?,bookstatus=? where bookid=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    //批量删除数据
    @Override
    public void batchDeleteBook(List<Object[]> batchArgs) {
        String sql = "delete from t_book where bookid=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }
}

BookService.java

package com.amhu.yx.spring.service;

import com.amhu.yx.spring.dao.Book;
import com.amhu.yx.spring.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class BookService {

    //注入dao
    @Autowired
    private BookDao bookDao;

    //添加数据
    public void insertBook(Book book){
        bookDao.insert(book);
    }

    //修改数据
    public void updateBook(Book book){
        bookDao.update(book);
    }

    //删除数据
    public void deleteBook(String id){
        bookDao.delete(id);
    }

    //查询数据库表中有多少条数据
    public void queryBookCount(){
        int count = bookDao.selectCount();
        System.out.println(count);
    }

    //查询一本书的相信信息
    public void queryBookInfo(String id){
        Book book = bookDao.queryBookInfo(id);
        System.out.println("bookid:" + book.getBookId());
        System.out.println("bookname:" + book.getBookName());
        System.out.println("bookstatus:" + book.getBookStatus());
    }

    //查询一页图书信息
    public void queryBookPage(){
        List<Book> bookList = bookDao.queryBookPage();
        for (Book book : bookList) {
            System.out.println("bookid:" + book.getBookId());
            System.out.println("bookname:" + book.getBookName());
            System.out.println("bookstatus:" + book.getBookStatus());
            System.out.println();
        }
    }

    //批量添加数据
    public void batchAddBook(List<Object[]> batchArgs){
        bookDao.batchAddBook(batchArgs);
    }

    //批量修改数据`在这里插入代码片`
    public void batchUpdateBook(List<Object[]> batchArgs){
        bookDao.batchUpdateBook(batchArgs);
    }

    //批量删除数据
    public void batchDeleteBook(List<Object[]> batchArgs){
        bookDao.batchDeleteBook(batchArgs);
    }
}

TestJdbcTemplate.java

package com.amhu.yx.spring.test;

import com.amhu.yx.spring.dao.Book;
import com.amhu.yx.spring.service.BookService;
import javafx.application.Application;
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 TestJdbcTemplate {
    ApplicationContext context = new ClassPathXmlApplicationContext("druidbean.xml");
    //测试添加数据
    @Test
    public void testInsert(){

        BookService bookService = context.getBean("bookService", BookService.class);
        Book book = new Book();
        book.setBookId("1");
        book.setBookName("Java 编程思想");
        book.setBookStatus("阅读中");
        bookService.insertBook(book);
    }

    @Test
    public void testUpdate(){
        BookService bookService = context.getBean("bookService", BookService.class);
        Book book = new Book();
        book.setBookId("1");
        book.setBookName("Thinking In Java");
        book.setBookStatus("Reading");
        bookService.updateBook(book);
    }

    @Test
    public void testDelete(){
        BookService bookService = context.getBean("bookService", BookService.class);
        bookService.deleteBook("1");
    }

    @Test
    public void testSelectCount() {
        BookService bookService = context.getBean("bookService", BookService.class);
        bookService.queryBookCount();
    }

    @Test
    public void testQueryBookInfo(){
        BookService bookService = context.getBean("bookService", BookService.class);
        bookService.queryBookInfo("1");
    }

    @Test
    public void testQueryBookPage(){
        BookService bookService = context.getBean("bookService", BookService.class);
        bookService.queryBookPage();
    }

    //批量添加数据
    @Test
    public void testBatchAddBook(){
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] book1 = {"3", "Python", "a"};
        Object[] book2 = {"4", "Scala", "b"};
        Object[] book3 = {"5", "C++", "c"};
        batchArgs.add(book1);
        batchArgs.add(book2);
        batchArgs.add(book3);
        bookService.batchAddBook(batchArgs);
    }
    //批量修改数据
    @Test
    public void testBatchUpdateBook(){
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] book1 = {"A","Python","3"};
        Object[] book2 = {"B","S","4"};
        Object[] book3 = {"C","C","5"};
        batchArgs.add(book1);
        batchArgs.add(book2);
        batchArgs.add(book3);
        bookService.batchUpdateBook(batchArgs);
    }

    //批量删除数据
    @Test
    public void testBatchDeleteBook(){
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] book1 = {"3"};
        Object[] book2 = {"4"};
        Object[] book3 = {"5"};
        batchArgs.add(book1);
        batchArgs.add(book2);
        batchArgs.add(book3);
        bookService.batchDeleteBook(batchArgs);
    }
}

你可能感兴趣的:(Spring)