JdbcTemplate学习与使用

JdbcTemplate

一、概述

关于Spring Data介绍
在这里插入图片描述

JdbcTemplate在org.springframework.jdbc.core这个包下面,是这个包的核心类。

Spring Framework对数据库的操作在JDBC上面做了深层次的封装,通过依赖注入功能,可以将 DataSource注册到JdbcTemplate之中,使我们可以轻易的完成对象关系映射,它简化了JDBC的使用和帮助避免常见错误,我们在SpringBoot中可以很轻松的使用。

特点:

  • 速度快,对比其它的ORM框架而言,JDBC的方式无异于是最快的
  • 配置简单,Spring自家出品,几乎没有额外配置
  • 学习成本低,毕竟JDBC是基础知识,JdbcTemplate更像是一个DBUtils

二、整合JdbcTemplate

2.1、添加依赖

pom.xml 文件里面添加 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- 父级依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.9</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <!-- 项目基本信息-->
    <groupId>edu.xja</groupId>
    <artifactId>springboot-gafdmc-rkqd</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-gafdmc-rkqd</name>
    <description>springboot-gafdmc-rkqd</description>
    <!-- 项目属性配置-->
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <!-- 项目依赖配置-->
    <dependencies>
        <!--        热部署依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!--        JdbcTemplate依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <!--        Thymeleaf依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--        web依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--        mysql连接驱动依赖包 mysql8.0-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--        lombok依赖包-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--        springboot单元测试依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--        springboot单元测试启动器-->
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-launcher</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!-- 项目构建配置-->
    <build>
        <!-- 指定打包后的项目名 -->
        <finalName>gafdmc-rkqd</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2.2、配置数据源

在springboot核心配置文件中添加如下配置。
值得注意的是,SpringBoot默认会 自动配置Datasource 它将优先采用 HikariCP 连接池,如果没有该依赖的情况,则选取 tomcat-jdbc,如果前两者都不可用最后选取 commons DBCP2。通过spring.datasource.type属性可以指定其它种类的连接池。

# 数据源

# mysql驱动版本在8以下就选择com.mysql.jdbc.Driver
# mysql驱动版本在8以及8以上就选择com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 省略了localhost:3306
spring.datasource.url=jdbc:mysql:///gafdm-rkqd?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
# 用户名
spring.datasource.username=root
# 密码
spring.datasource.password=

2.3、查看日志

启动项目,通过日志,可以看到默认情况下注入的是 Hikaridatasource
在这里插入图片描述
在这里插入图片描述

2.4、案例测试

单表的增删改查

案例:广安防盗门厂 入库清单
在这里插入图片描述

2.4.1、数据库表
2.4.1.1、数据表:category
/*
 Navicat Premium Data Transfer

 Source Server         : mysql8.0
 Source Server Type    : MySQL
 Source Server Version : 80031
 Source Host           : localhost:3306
 Source Schema         : gafdm-rkqd

 Target Server Type    : MySQL
 Target Server Version : 80031
 File Encoding         : 65001
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for category
-- ----------------------------
DROP TABLE IF EXISTS `category`;
CREATE TABLE `category`  (
  `category_id` int NOT NULL AUTO_INCREMENT COMMENT '分类编号',
  `category_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '分类名称',
  PRIMARY KEY (`category_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 22 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of category
-- ----------------------------
INSERT INTO `category` VALUES (1, '钢质防火门');
INSERT INTO `category` VALUES (2, '\r\n木质防火门');
INSERT INTO `category` VALUES (3, '\r\n钢木质防火门');
INSERT INTO `category` VALUES (7, '防火玻璃门');
INSERT INTO `category` VALUES (8, '防火卷帘门');
INSERT INTO `category` VALUES (9, '密闭门');
INSERT INTO `category` VALUES (16, '新型钢材防盗门');

SET FOREIGN_KEY_CHECKS = 1;
2.4.1.2、数据表:cargo
/*
 Navicat Premium Data Transfer

 Source Server         : mysql8.0
 Source Server Type    : MySQL
 Source Server Version : 80031
 Source Host           : localhost:3306
 Source Schema         : gafdm-rkqd

 Target Server Type    : MySQL
 Target Server Version : 80031
 File Encoding         : 65001
 
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for cargo
-- ----------------------------
DROP TABLE IF EXISTS `cargo`;
CREATE TABLE `cargo`  (
  `cargo_id` int NOT NULL AUTO_INCREMENT COMMENT '货物编号',
  `cargo_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '货物名称',
  `cargo_units` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '货物计量单位',
  `cargo_num` int NULL DEFAULT NULL COMMENT '货物数量',
  `cargo_price` double(20, 2) NULL DEFAULT NULL COMMENT '货物价格',
  `cargo_manufacturer` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '生产厂家',
  `category_id` int NULL DEFAULT NULL COMMENT '所属分类',
  `cargo_warehouse_entry_time` datetime NULL DEFAULT NULL COMMENT '入库时间',
  `cargo_operator` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '操作员',
  PRIMARY KEY (`cargo_id`) USING BTREE,
  INDEX `category_id`(`category_id` ASC) USING BTREE,
  CONSTRAINT `cargo_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of cargo
-- ----------------------------
INSERT INTO `cargo` VALUES (1, '博物馆金库门碳钢库房防盗门 银行钢制金库大门防尾随门', '100kg', 556, 10000.00, '河北涞港智能科技有限公司', 1, '2023-02-21 15:00:40', '张丰');
INSERT INTO `cargo` VALUES (2, '广安别墅金库门碳钢防盗门 雅安地下室密室门不锈钢门定制', '80kg', 556, 10000.00, '河北涞港智能科技有限公司', 3, '2023-01-25 15:03:38', '牛涛');
INSERT INTO `cargo` VALUES (3, '创鑫钢质门 防盗门 四川防火门厂家 广元德阳广安甘孜西昌工程门厂家直销厂家定制', '60kg', 73, 398.00, '成都市吉瑞名城科技有限公司', 3, '2020-06-19 15:06:50', '王晓明');
INSERT INTO `cargo` VALUES (4, '森森厂家定制钢制净化门 不锈钢耐磨防火门 可定制防盗门厂家批发', '80kg', 3544, 600.00, '德州市森森木业有限公司', 1, '2021-07-20 15:09:01', '李建国');
INSERT INTO `cargo` VALUES (7, '11', '11', 11, 111.20, 'dsfdsfsf', 9, '2023-03-23 20:45:42', 'sfssfdf');
INSERT INTO `cargo` VALUES (11, 'ww', 'www', 12, 1212.23, 'eqwe', 2, '2023-03-23 08:49:15', '11111');
INSERT INTO `cargo` VALUES (12, 'aaa', 'aaa', 1020, 120.25, 'aaa', 1, '2023-03-06 00:22:48', 'aaa');
INSERT INTO `cargo` VALUES (13, '厂家定做储藏室地下室防盗门 地上储藏室双层板复合门 大量供应', '80kg', 3544, 688.00, '德州市森森木业有限公司', 1, '2019-04-19 14:29:56', '刘刚刚');

SET FOREIGN_KEY_CHECKS = 1;
2.4.2、实体类
2.4.2.1、实体类:Category
package edu.xja.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author: xxx
 * @Date: xxx
 * @description: xxx
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Category {
   

    /**
     * 分类编号
     */
    private Integer categoryId;
    /**
     * 分类名称
     */
    private String categoryName;
}
2.4.2.2、实体类:Cargo
package edu.xja.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

/**
 * @author: xxx
 * @Date: xxxx
 * @description: xxx
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Cargo {
   
    /**
     * 货物编号
     */
    private Integer cargoId;
    /**
     * 货物名称
     */
    private String cargoName;
    /**
     * 货物计量单位
     */
    private String cargoUnits;
    /**
     * 货物数量
     */
    private Integer cargoNum;
    /**
     * 货物价格
     */
    private Double cargoPrice;
    /**
     * 生产厂家
     */
    private String cargoManufacturer;
    /**
     * 所属分类
     */
    private Integer categoryId;
    /**
     * 入库时间
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date cargoWarehouseEntryTime;
    /**
     * 操作员
     */
    private String cargoOperator;

    /**
     * category
     */
    private Category category;
}
2.4.2.3、搜索查询类:SearchCargoVO
package edu.xja.dao.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

/**
 * @author: xxx
 * @Date: xxx
 * @description: 广安防盗门厂入库清单 防盗门货物信息 多种查询条件VO类
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
public class SearchCargoVO {
   

    /**
     * 货物名称 快速查询 模糊查询
     */
    private String cargoName;

    /**
     * 货物入库时间 快速查询
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date cargoWarehouseEntryTime;

}
2.4.3、控制层
2.4.3.1、控制层类:CategoryController
package edu.xja.controller;

import edu.xja.entity.Cargo;
import edu.xja.entity.Category;
import edu.xja.service.CargoService;
import edu.xja.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author: xxx
 * @Date: xxx
 * @description: xxx
 */

@Controller
@RequestMapping("/category")
public class CategoryController {
   

    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有防盗门分类信息
     *
     * @param model
     * @return
     */
    @RequestMapping("/queryList")
    public String queryList(Model model) {
   
        List<Category> categoryList = categoryService.queryList();
        model.addAttribute("categoryList", categoryList);
        return "category_list"
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值