Spring之JdbcTemplate(带你一篇文章搞定JdbcTemplate)

文章目录

  • 前言
  • 一、相关依赖(AOP、IOC、JdbcTemplate都有)
  • 二、代码实战
    • 1.方法讲解
    • 2.代码实例
  • 总结


前言

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


一、相关依赖(AOP、IOC、JdbcTemplate都有)

        <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>spring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.9.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>6.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>6.0.9</version>
        </dependency>
        <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.2</version>
            </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>6.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>6.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.19</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.cglib</groupId>
            <artifactId>com.springsource.net.sf.cglib</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>6.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>6.0.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>6.0.9</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>compile</scope>
        </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.9.19</version>
            </dependency>
    </dependencies>
</project>

二、代码实战

1.方法讲解

  • 增删改:
int update(String sql, Object... args);
  • 查询(返回某个值):
T queryForObject(String sql,Class<T> requiredType);
  • 查询(返回某个对象):
T queryForObject(String sql,Class<T> requiredType);
  • 查询(返回集合):
List<T> query(String sql,RowMapper<T> rowMapper,Object... args);
  • 批量增删改:
int[] batchUpdate(String sql,List<Object[]> batchArgs);

2.代码实例

实体层——Book实体类:

package com.dragon.jdbc.entity;

public class Book {
    private String bookId;
    private String bookname;
    private String bstatus;

    public String getBookId() {
        return bookId;
    }

    public String getBookname() {
        return bookname;
    }

    public String getBstatus() {
        return bstatus;
    }

    public void setBookId(String bookId) {
        this.bookId = bookId;
    }

    public void setBookname(String bookname) {
        this.bookname = bookname;
    }

    public void setBstatus(String bstatus) {
        this.bstatus = bstatus;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookId='" + bookId + '\'' +
                ", bookname='" + bookname + '\'' +
                ", bstatus='" + bstatus + '\'' +
                '}';
    }
}

Dao层——BookDao类:

package com.dragon.jdbc.dao;

import com.dragon.jdbc.entity.Book;

import java.util.List;

public interface BookDao {
    public void add(Book book);//添加
    public void update(Book book);//修改更新
    public void delete(String id);//删除
    public int selectCount();//查找数量,返回int类型
    public Book findBookInfo(String id);//根据id查找某本书,返回对象
    public List<Book> findAllBook();//查找数据库内所有对象,返回集合
    public void bathAddBook(List<Object[]> bathArgs);//批量添加
    public void bathUpdateBook(List<Object[]> bathArgs);//批量修改
    public void bathDeleteBook(List<Object[]> bathArgs);//批量删除
}

BookDao实现类BookDaoImpl:

package com.dragon.jdbc.dao;

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

@Repository
public class BookDaoImpl implements BookDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void add(Book book) {
        String sql="insert into t_book values(?,?,?)";
        Object[] args={book.getBookId(),book.getBookname(),book.getBstatus()};
        int update=jdbcTemplate.update(sql,args);
        System.out.println(update);
    }

    @Override
    public void update(Book book) {
        String sql="update t_book set bookname=?,bstatus=? where book_id=?";
        Object[] args={book.getBookname(),book.getBstatus(),book.getBookId()};
        int update=jdbcTemplate.update(sql,args);
        System.out.println(update);
    }

    @Override
    public void delete(String id) {
        String sql="delete from t_book where book_id=?";
        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;
    }

    @Override
    public Book findBookInfo(String id) {
        String sql="select * from t_book where book_id=?";
        Book book= jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Book>(Book.class),id);
        return book;
    }

    @Override
    public List<Book> findAllBook() {
        String sql="select * from t_book";
        List<Book> bookList=jdbcTemplate.query(sql,new BeanPropertyRowMapper<Book>(Book.class));
        return bookList;
    }

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

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

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


}

service层——BookService:

package com.dragon.jdbc.service;

import com.dragon.jdbc.dao.BookDao;
import com.dragon.jdbc.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookService {
    @Autowired
    private BookDao bookDao;

    public void addBook(Book book){
        bookDao.add(book);
    }
    public void updateBook(Book book){
        bookDao.update(book);
    }
    public void deleteBook(String id){
        bookDao.delete(id);
    }
    public int findCount(){
       return bookDao.selectCount();
    }
    public Book finOne(String id){
        return bookDao.findBookInfo(id);
    }
    public List<Book> findAll(){
        return bookDao.findAllBook();
    }
    public void bathAdd(List<Object[]> bathArgs){
        bookDao.bathAddBook(bathArgs);
    }
    public void bathUpdate(List<Object[]> bathArgs){
        bookDao.bathUpdateBook(bathArgs);
    }
    public void bathDelete(List<Object[]> bathArgs){
        bookDao.bathDeleteBook(bathArgs);
    }
}

数据库连接配置——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">
        <context:property-placeholder location="classpath:jdbc.properties"/>
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="${pro.driverClass}"></property>
                <property name="url" value="${pro.url}"></property>
                <property name="username" value="${pro.username}"></property>
                <property name="password" value="${pro.password}"></property>
        </bean>
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
                <property name="dataSource" ref="dataSource"></property>
        </bean>
        <context:component-scan base-package="com.dragon.jdbc"></context:component-scan>
</beans>

properties配置文件——jdbc.properties:
需要自行修改数据库名称(我的是user_db)

pro.driverClass=com.mysql.cj.jdbc.Driver
pro.url=jdbc:mysql://localhost:3306/user_db?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false
pro.username=root
pro.password=root

测试类:

package com.dragon.jdbc.test;

import com.dragon.jdbc.entity.Book;
import com.dragon.jdbc.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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

public class test1 {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean8.xml");
        BookService bookService=context.getBean("bookService",BookService.class);
//        Book book=new Book();
//        book.setBookId("1");
//        book.setBookname("java");
//        book.setBstatus("a");
//        bookService.addBook(book);

//        Book book=new Book();
//        book.setBookId("1");
//        book.setBookname("javaup");
//        book.setBstatus("a");
//        bookService.updateBook(book);

//        bookService.deleteBook("1");

//        System.out.println( bookService.findCount());

//        Book book=bookService.finOne("1");
//        System.out.println(book);

//        System.out.println(bookService.findAll());

//        List bathArgs=new ArrayList<>();
//        Object[] o1={"3","java","j"};
//        Object[] o2={"4","c++","c"};
//        Object[] o3={"5","MySql","m"};
//        bathArgs.add(o1);
//        bathArgs.add(o2);
//        bathArgs.add(o3);
//        bookService.bathAdd(bathArgs);

//        List bathArgs=new ArrayList<>();
//        Object[] o1={"java001","j","3"};
//        Object[] o2={"c++002","c","4"};
//        Object[] o3={"MySql003","m","5"};
//        bathArgs.add(o1);
//        bathArgs.add(o2);
//        bathArgs.add(o3);
//        bookService.bathUpdate(bathArgs);

        List<Object[]> bathArgs=new ArrayList<>();
        Object[] o1={"3"};
        Object[] o2={"4"};
        bathArgs.add(o1);
        bathArgs.add(o2);
        bookService.bathDelete(bathArgs);
    }

}

总结

这部分内容不需要多么详细讲解,你只要看一下封装好的那些方法是用来做什么操作的,返回值是什么,传入的参数是什么,然后就会使用了。

你可能感兴趣的:(Spring,spring,数据库,sqlserver,JdbcTemplate)