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";
}
/***
* 根据分类编号查询防盗门分类信息
*
* @param categoryId
* @return
*/
@RequestMapping("/queryCategoryByCategoryId")
public String queryCategoryByCategoryId(Integer categoryId) {
Category category = categoryService.queryCategoryByCategoryId(categoryId);
return "category_list";
}
/**
* 去分类添加页面 并携带数据
*
* @param
* @return
*/
@RequestMapping("/toSave")
public String toSave() {
return "category_add";
}
/**
* 添加防盗门分类信息
*
* @param category
* @return
*/
@RequestMapping("/saveCategory")
public String saveCategory(Category category) {
int i = categoryService.saveCategory(category);
return i > 0 ? "redirect:/category/queryList" : "error";
}
/**
* 去修改页面 并携带数据
*
* @return
*/
@RequestMapping("/toUpdate")
public String toUpdate(Model model, int categoryId) {
Category category = categoryService.queryCategoryByCategoryId(categoryId);
model.addAttribute("category", category);
return "category_edit";
}
/**
* 修改防盗门分类信息
*
* @param category
* @return
*/
@RequestMapping("/updateCategory")
public String updateCategory(Category category) {
int i = categoryService.updateCategory(category);
return i > 0 ? "redirect:/category/queryList" : "error";
}
/**
* 删除防盗门分类信息
*
* @param categoryId
* @return
*/
@RequestMapping("/deleteCategory")
public String deleteCategory(Integer categoryId) {
int i = categoryService.deleteCategory(categoryId);
return i > 0 ? "redirect:/category/queryList" : "error";
}
}
2.4.3.2、控制层类:CargoController
package edu.xja.controller;
import edu.xja.dao.vo.SearchCargoVO;
import edu.xja.entity.Cargo;
import edu.xja.entity.Category;
import edu.xja.service.CargoService;
import edu.xja.service.CategoryService;
import edu.xja.utils.PageInfo;
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 org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author: xxx
* @Date: xxx
* @description: xxx
*/
@Controller
@RequestMapping("/cargo")
public class CargoController {
@Autowired
private CargoService cargoService;
@Autowired
private CategoryService categoryService;
/**
* 查询所有防盗门货物信息
*
* @return
*/
@RequestMapping("/queryList")
public String queryList(Model model,
@RequestParam(value = "pageNum", defaultValue = "1", required = false) int pageNum,
@RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize
) {
// 获取总记录数
Integer cargoTotal = cargoService.queryCargoTotal();
// pageInfo对象
PageInfo<Cargo> cargoPageInfo = new PageInfo<>(pageNum, pageSize, cargoTotal);
// 查询cargo数据
List<Cargo> cargoList = cargoService.queryList(cargoPageInfo);
cargoPageInfo.setList(cargoList);
model.addAttribute("pageInfo", cargoPageInfo);
return "cargo_list";
}
/**
* 查询所有防盗门货物信息 快速查询
*
* @return
*/
@RequestMapping("/queryListByCargoNameAndCargoWarehouseEntryTime")
public String queryListByCargoNameAndCargoWarehouseEntryTime(SearchCargoVO scVO) {
List<Cargo> cargoList = cargoService.queryListByCargoNameAndCargoWarehouseEntryTime(scVO);
return "redirect:/cargo/queryList";
}
/***
* 去分类添加页面 并携带数据
*
* @param model
* @return
*/
@RequestMapping("/toSave")
public String toSave(Model model) {
List<Category> categoryList = categoryService.queryList();
model.addAttribute("categoryList", categoryList);
return "cargo_add";
}
/**
* 添加防盗门货物信息
*
* @return
*/
@RequestMapping("/saveCargo")
public String saveCargo(Cargo cargo) {
int i = cargoService.saveCargo(cargo);
return i > 0 ? "redirect:/cargo/queryList" : "error";
}
/**
* 去修改页面 并携带数据
*
* @param model
* @param cargoId
* @return
*/
@RequestMapping("/toUpdate")
public String toUpdate(Model model, int cargoId) {
Cargo cargo = cargoService.queryCargoByCargoId(cargoId);
model.addAttribute("cargo", cargo);
List<Category> categoryList = categoryService.queryList();
model.addAttribute("categoryList", categoryList);
return "cargo_edit";
}
/**
* 修改防盗门货物信息
*
* @return
*/
@RequestMapping("/updateCargo")
public String updateCargo(Cargo cargo) {
int i = cargoService.updateCargo(cargo);
return i > 0 ? "redirect:/cargo/queryList" : "error";
}
/**
* 根据货物编号删除防盗门货物信息
*
* @param cargoId
* @return
*/
@RequestMapping("/deleteCargo")
public String deleteCargo(int cargoId) {
int i = cargoService.deleteCargo(cargoId);
return i > 0 ? "redirect:/cargo/queryList" : "error";
}
}
2.4.4、业务层接口(没有业务)
2.4.4.1、业务层接口:CategoryService
package edu.xja.service;
import edu.xja.entity.Category;
import java.util.List;
/**
* @author: xxx
* @Date: xxx
* @description: xxx
*/
public interface CategoryService {
/**
* 查询所有防盗门分类信息
*
* @return
*/
List<Category> queryList();
/**
* 根据分类编号查询防盗门分类信息
*
* @return
*/
Category queryCategoryByCategoryId(Integer categoryId);
/**
* 添加防盗门分类信息
*
* @param category
* @return
*/
int saveCategory(Category category);
/**
* 修改防盗门分类信息
*
* @param category
* @return
*/
int updateCategory(Category category);
/**
* 删除防盗门分类信息
*
* @param categoryId
* @return
*/
int deleteCategory(Integer categoryId);
}
2.4.4.2、业务层接口:CargoService
package edu.xja.service;
import edu.xja.dao.vo.SearchCargoVO;
import edu.xja.entity.Cargo;
import edu.xja.utils.PageInfo;
import java.util.List;
/**
* @author: xxx
* @Date: xxx
* @description: xxx
*/
public interface CargoService {
/**
* 查询所有防盗门货物信息
*
* @return
* @param cargoPageInfo
*/
List<Cargo> queryList(PageInfo<Cargo> cargoPageInfo);
/**
* 查询所有防盗门货物信息 多条件查询
*
* @return
*/
List<Cargo> queryListByCargoNameAndCargoWarehouseEntryTime(SearchCargoVO scVO);
/**
* 查询所有防盗门货物信息 模糊查询货物名称
*
* @return
*/
List<Cargo> queryListLikeCargoNameAndByCargoWarehouseEntryTime(SearchCargoVO scVO);
/**
* 添加防盗门货物信息
*
* @return
*/
int saveCargo(Cargo cargo);
/**
* 修改防盗门货物信息
*
* @return
*/
int updateCargo(Cargo cargo);
/**
* 根据货物编号删除防盗门货物信息
*
* @param cargoId
* @return
*/
int deleteCargo(int cargoId);
/**
* 去修改页面 并携带数据
*
* @param
* @param cargoId
* @return
*/
Cargo queryCargoByCargoId(int cargoId);
Integer queryCargoTotal();
}
2.4.5、业务层接口的实现类(没有业务)
2.4.5.1、业务层接口的实现类:CategoryServiceImpl
package edu.xja.service.impl;
import edu.xja.dao.CategoryDao;
import edu.xja.entity.Category;
import edu.xja.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @author: xxx
* @Date: xxx
* @description: xxx
*/
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
@Autowired
private CategoryDao categoryDao;
/**
* 查询所有防盗门分类信息
*
* @return
*/
@Override
public List<Category> queryList() {
return categoryDao.queryList();
}
/**
* 根据分类编号查询防盗门分类信息
*
* @param categoryId
* @return
*/
@Override
public Category queryCategoryByCategoryId(Integer categoryId) {
return categoryDao.queryCategoryByCategoryId(categoryId);
}
/**
* 添加防盗门分类信息
*
* @param category
* @return
*/
@Override
public int saveCategory(Category category) {
return categoryDao.saveCategory(category);
}
/**
* 修改防盗门分类信息
*
* @param category
* @return
*/
@Override
public int updateCategory(Category category) {
return categoryDao.updateCategory(category);
}
/**
* 删除防盗门分类信息
*
* @param categoryId
* @return
*/
@Override
public int deleteCategory(Integer categoryId) {
return categoryDao.deleteCategory(categoryId);
}
}
2.4.5.2、业务层接口的实现类:CargoServiceImpl
package edu.xja.service.impl;
import edu.xja.dao.CargoDao;
import edu.xja.dao.CategoryDao;
import edu.xja.dao.vo.SearchCargoVO;
import edu.xja.entity.Cargo;
import edu.xja.entity.Category;
import edu.xja.service.CargoService;
import edu.xja.utils.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.util.List;
/**
* @author: xxx
* @Date: xxx
* @description: some description
*/
@Service
@Transactional
public class CargoServiceImpl implements CargoService {
@Autowired
private CargoDao cargoDao;
@Autowired
private CategoryDao categoryDao;
/**
* 查询所有防盗门货物信息
*
* @return
* @param cargoPageInfo
*/
@Override
public List<Cargo> queryList(PageInfo<Cargo> cargoPageInfo) {
List<Cargo> cargoList = cargoDao.queryList(cargoPageInfo);
List<Category> categoryList = categoryDao.queryList();
cargoList.forEach(cargo -> {
Category category = categoryDao.queryCategoryByCategoryId(cargo.getCategoryId());
cargo.setCategory(category);
});
return cargoList;
}
/**
* 查询所有防盗门货物信息 多条件查询
*
* @param scVO
* @return
*/
@Override
public List<Cargo> queryListByCargoNameAndCargoWarehouseEntryTime(SearchCargoVO scVO) {
return cargoDao.queryListByCargoNameAndCargoWarehouseEntryTime(scVO);
}
/**
* 查询所有防盗门货物信息 模糊查询货物名称
*
* @param scVO
* @return
*/
@Override
public List<Cargo> queryListLikeCargoNameAndByCargoWarehouseEntryTime(SearchCargoVO scVO) {
return cargoDao.queryListLikeCargoNameAndByCargoWarehouseEntryTime(scVO);
}
/**
* 添加防盗门货物信息
*
* @param cargo
* @return
*/
@Override
public int saveCargo(Cargo cargo) {
int res = 0;
try {
int i = cargoDao.saveCargo(cargo);
if(i > 0){
res = 1;
}
} catch (Exception e) {
e.printStackTrace();
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
res = 0;
}
return res;
}
/**
* 修改防盗门货物信息
*
* @param cargo
* @return
*/
@Override
public int updateCargo(Cargo cargo) {
return cargoDao.updateCargo(cargo);
}
/**
* 根据货物编号删除防盗门货物信息
*
* @param cargoId
* @return
*/
@Override
public int deleteCargo(int cargoId) {
return cargoDao.deleteCargo(cargoId);
}
/**
* 去修改页面 并携带数据
*
* @param cargoId
* @return
*/
@Override
public Cargo queryCargoByCargoId(int cargoId) {
return cargoDao.queryCargoByCargoId(cargoId);
}
@Override
public Integer queryCargoTotal() {
return cargoDao.queryCargoTotal();
}
}
2.5.6、持久层
2.5.6.1、持久层类:CategoryDao
package edu.xja.dao;
import edu.xja.entity.Category;
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.List;
/**
* @author: xxx
* @Date: xxx
* @description: xxx
*/
@Repository
public class CategoryDao {
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 查询所有防盗门分类信息
*
* @return
*/
public List<Category> queryList() {
String sql = "select c.* from category c";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Category.class));
}
/**
* 根据分类编号查询防盗门分类信息
*
* @param categoryId
* @return
*/
public Category queryCategoryByCategoryId(Integer categoryId) {
String sql = "select c.* from category c where c.category_id = ?";
Category category = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Category.class), categoryId);
return category;
}
/**
* 添加防盗门分类信息
*
* @param category
* @return
*/
public int saveCategory(Category category) {
String sql = "insert into category(category_name) value(?)";
int i = jdbcTemplate.update(sql, category.getCategoryName());
return i;
}
/**
* 修改防盗门分类信息
*
* @param category
* @return
*/
public int updateCategory(Category category) {
String sql = "update category c set c.category_name = ? where c.category_id = ?";
int i = jdbcTemplate.update(sql, category.getCategoryName(), category.getCategoryId());
return i;
}
/**
* 删除防盗门分类信息
*
* @param categoryId
* @return
*/
public int deleteCategory(Integer categoryId) {
String sql = "delete from category c where c.category_id = ?";
return jdbcTemplate.update(sql, categoryId);
}
}
2.5.6.2、持久层类:CargoDao
package edu.xja.dao;
import edu.xja.dao.vo.SearchCargoVO;
import edu.xja.entity.Cargo;
import edu.xja.entity.Category;
import edu.xja.utils.PageInfo;
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 javax.swing.text.Caret;
import java.util.List;
/**
* @author: xxx
* @Date: xxx
* @description: some description
*/
@Repository
public class CargoDao {
@Autowired
private JdbcTemplate jdbcTemplate;
/**
* 查询所有防盗门货物信息
*
* @param cargoPageInfo
* @return
*/
public List<Cargo> queryList(PageInfo<Cargo> cargoPageInfo) {
String sql = "select c.* from cargo c limit ?,?";
List<Cargo> cargoList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Cargo.class), cargoPageInfo.getStartIndex(), cargoPageInfo.getPageSize());
return cargoList;
}
/**
* 查询所有防盗门货物信息 多条件查询
*
* @param scVO
* @return
*/
public List<Cargo> queryListByCargoNameAndCargoWarehouseEntryTime(SearchCargoVO scVO) {
String sql = "select c.* from cargo c where c.cargo_name = ? and c.cargo_warehouse_entry_time = ?";
List<Cargo> cargoList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Cargo.class), scVO.getCargoName(), scVO.getCargoWarehouseEntryTime());
return cargoList;
}
/**
* 查询所有防盗门货物信息 模糊查询货物名称
*
* @param scVO
* @return
*/
public List<Cargo> queryListLikeCargoNameAndByCargoWarehouseEntryTime(SearchCargoVO scVO) {
String sql = "select c.* from cargo c where c.cargo_name like ? and c.cargo_warehouse_entry_time = ?";
List<Cargo> cargoList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Cargo.class), "%" + scVO.getCargoName() + "%", scVO.getCargoWarehouseEntryTime());
return cargoList;
}
/**
* 添加防盗门货物信息
*
* @param cargo
* @return
*/
public int saveCargo(Cargo cargo) {
String sql = "insert into cargo(cargo_name, cargo_units, cargo_num, cargo_price, cargo_manufacturer, category_id, cargo_warehouse_entry_time, cargo_operator) value(?, ?, ?, ?, ?, ?, ?, ?)";
int i = jdbcTemplate.update(sql, cargo.getCargoName(), cargo.getCargoUnits(), cargo.getCargoNum(), cargo.getCargoPrice(), cargo.getCargoManufacturer(), cargo.getCategoryId(), cargo.getCargoWarehouseEntryTime(), cargo.getCargoOperator());
return i;
}
/**
* 修改防盗门货物信息
*
* @param cargo
* @return
*/
public int updateCargo(Cargo cargo) {
String sql = "update cargo c set c.cargo_name = ?,c.cargo_units = ?, c.cargo_num = ?, c.cargo_price = ?, c.cargo_manufacturer = ?, c.category_id = ?, c.cargo_warehouse_entry_time = ?, c.cargo_operator = ? where c.cargo_id = ?";
return jdbcTemplate.update(sql, cargo.getCargoName(), cargo.getCargoUnits(), cargo.getCargoNum(), cargo.getCargoPrice(), cargo.getCargoManufacturer(), cargo.getCategoryId(), cargo.getCargoWarehouseEntryTime(), cargo.getCargoOperator(), cargo.getCargoId());
}
/**
* 根据货物编号删除防盗门货物信息
*
* @param cargoId
* @return
*/
public int deleteCargo(int cargoId) {
String sql = "delete from cargo c where c.cargo_id = ?";
int i = jdbcTemplate.update(sql, cargoId);
return i;
}
/**
* 去修改页面 并携带数据
*
* @param cargoId
* @return
*/
public Cargo queryCargoByCargoId(int cargoId) {
String sql = "select c.* from cargo c where c.cargo_id = ?";
Cargo cargo = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Cargo.class), cargoId);
return cargo;
}
public Integer queryCargoTotal() {
String sql = "select count(*) from cargo";
return jdbcTemplate.queryForObject(sql, Integer.class);
}
}
2.5.7、配置类
2.5.7.1、配置类:WelcomePageConfig
package edu.xja.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author: xxx
* @Date: xxx
* @description: xxx
*/
@Configuration
public class WelcomePageConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/").setViewName("index.html");
}
}
2.5.8、工具类
2.5.8.1、分页工具类:PageInfo
package edu.xja.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* @author: xxx
* @Date: xxx
* @description: some description
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageInfo<T> {
private int pageNum; // 当前页
private int PageSize; // 每页显示数据条数
private int total; // 总记录数
private int pages; // 总页数
private int firstPage; // 首页
private int lastPage; // 尾页
private int prePage; // 上一页
private int nextPage; //下一页
private int paginationNavs; // 分页导航
private int startIndex; // 开始索引
private List<T> list; // 返回数据
public PageInfo(int pageNum, int pageSize, int total) {
this.pageNum = pageNum;
this.PageSize = pageSize;
this.total = total;
// 计算总页数
this.pages = (this.total / this.PageSize) + (this.total % this.PageSize == 0 ? 0 : 1);
// 计算首页
this.firstPage = 1;
// 计算尾页
this.lastPage = this.pages;
// 计算上一页
this.prePage = this.pageNum > 1 ? this.pageNum - 1 : 1;
// 计算下一页
this.nextPage = this.pageNum >= this.pages ? this.pages : this.pageNum + 1;
// 计算分页导航
this.paginationNavs = this.pages;
// 计算开始索引 起始索引 (当前页 -1 ) * pageSize
this.startIndex = (this.pageNum - 1) * this.PageSize;
}
}
2.5.8、前端页面
2.5.8.1、分类前端展示页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>category_list</title>
<link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
<script type="text/javascript" th:src="@{/js/jquery-3.6.0.js}"></script>
<style type="text/css">
#category_div {
width: 400px;
margin-left: 20px;
margin-top: 20px;
}
#category_tb {
text-align: center;
}
#category_tb thead tr th {
text-align: center;
}
#category_tb tbody tr td {
line-height: 2;
}
</style>
</head>
<body>k
<div id="category_div">
<span style="color: #FF2F2F;">port:8082</span>
<table class="table table-bordered table-hover" id="category_tb">
<thead>
<tr>
<th>分类编号</th>
<th>分类名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="category,index : ${categoryList}">
<td th:text="${index.count}"></td>
<td th:text="${category.categoryName}"></td>
<td>
<button type="button" class="btn btn-danger btn-sm"
th:onclick="|toEditAndEditCategory(${category.categoryId})|">编辑
</button>
<button type="button" class="btn btn-danger btn-sm"
th:onclick="|deleteCategoryByCategoryId(${category.categoryId})|">删除
</button>
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-danger btn-sm" id="category_add_btn">添加</button>
</div>
<script type="text/javascript">
function toEditAndEditCategory(categoryId) {
window.location.href = "/category/toUpdate?categoryId=" + categoryId;
}
function deleteCategoryByCategoryId(categoryId) {
confirm("你确定要删除该广安防盗门分类吗?") ? window.location.href = "/category/deleteCategory?categoryId=" + categoryId : window.location.href = "/category/queryList";
}
$(function () {
$("#category_add_btn").click(function () {
window.location.href = "/category/toSave";
});
})
</script>
</body>
</html>
2.5.8.2、分类前端添加页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>category_add</title>
<link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
<script type="text/javascript" th:src="@{/js/jquery-3.6.0.js}"></script>
<style type="text/css">
#category_add_div {
width: 400px;
margin-left: 20px;
margin-top: 20px;
}
</style>
</head>
<body>
<div id="category_add_div" class="form-inline">
<form action="/category/saveCategory" method="post" id="category_add_form">
<div class="form-group">
<label for="category_name">分类名称:</label>
<input type="text" class="form-control" name="categoryName" id="category_name" placeholder="分类名称...">
</div>
<button type="submit" class="btn btn-danger btn-sm">保存</button>
</form>
</div>
</body>
</html>
2.5.8.3、分类前端修改页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>category_edit</title>
<link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
<script type="text/javascript" th:src="@{/js/jquery-3.6.0.js}"></script>
<style type="text/css">
#category_edit_div {
width: 400px;
margin-left: 20px;
margin-top: 20px;
}
</style>
</head>
<body>
<div id="category_edit_div" class="form-inline">
<form action="/category/updateCategory" method="post" id="category_add_form">
<input type="hidden" name="categoryId" th:value="${category.categoryId}"/>
<div class="form-group">
<label for="category_name">分类名称:</label>
<input type="text" class="form-control" name="categoryName" id="category_name" placeholder="分类名称..." th:value="${category.categoryName}">
</div>
<button type="submit" class="btn btn-danger btn-sm">保存</button>
</form>
</div>
</body>
</html>
2.5.8.4、货物前端展示页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>cargo_list</title>
<link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
<script type="text/javascript" th:src="@{/js/jquery-3.6.0.js}"></script>
<style type="text/css">
#cargo_div {
width: 1500px;
margin-left: 20px;
margin-top: 20px;
}
#cargo_tb {
text-align: center;
}
#cargo_tb thead tr th {
text-align: center;
}
#cargo_tb tbody tr td {
line-height: 2;
}
</style>
</head>
<body>
<div id="cargo_div">
<span style="color: #FF2F2F;">port:8082</span>
<table class="table table-bordered table-hover" id="cargo_tb">
<thead>
<tr>
<th>货物编号</th>
<th>货物名称</th>
<th>货物计量单位</th>
<th>货物数量</th>
<th>货物价格</th>
<th>生产厂家</th>
<th>所属分类</th>
<th>入库时间</th>
<th>操作员</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr th:each="cargo,index : ${pageInfo.list}" th:object="${cargo}">
<td th:text="${index.count}"></td>
<!-- <td th:text="|*{#strings.substring(cargoName,0,5)}...|"></td>-->
<td th:text="${cargo.cargoName}"></td>
<td th:text="*{cargoUnits}"></td>
<td th:text="*{cargoNum}"></td>
<td th:text="*{cargoPrice}"></td>
<td th:text="*{cargoManufacturer}"></td>
<td th:text="*{category.categoryName}"></td>
<td th:text="*{#dates.format(cargoWarehouseEntryTime,'yyyy-MM-dd HH:mm:ss')}"></td>
<td th:text="*{cargoOperator}"></td>
<td>
<button type="button" class="btn btn-danger btn-sm"
th:onclick="|toEditAndEditCargo(${cargo.cargoId})|">编辑
</button>
<button type="button" class="btn btn-danger btn-sm"
th:onclick="|deleteCargoByCargoId(${cargo.cargoId})|">删除
</button>
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-danger btn-sm" id="cargo_add_btn">添加</button>
<div id="cargo_pagination">
<span>总计<b th:text="${pageInfo.total}"></b>条记录,当前是<b th:text="${pageInfo.pageNum}"></b> / <b
th:text="${pageInfo.pages}"></b>页</span><br>
<div id="cargo_paging_btn">
<button th:onclick="|paginationQuery(${pageInfo.firstPage})|">首页</button>
<button th:onclick="|paginationQuery(${pageInfo.prePage})|">上一页</button>
<button th:each="nav,index : ${pageInfo.paginationNavs}" th:onclick="|paginationQuery(${nav})|"
th:text="${index.count+1}"></button>
<button th:onclick="|paginationQuery(${pageInfo.nextPage})|">下一页</button>
<button th:onclick="|paginationQuery(${pageInfo.lastPage})|">尾页</button>
<select name="pageSize" id="paging_sel">
<option value="">--请选择--</option>
<option th:selected="${pageInfo.pageSize}" value="2">2</option>
<option th:selected="${pageInfo.pageSize}" value="4">4</option>
<option th:selected="${pageInfo.pageSize}" value="5">5</option>
<option th:selected="${pageInfo.pageSize}" value="10">10</option>
</select>
</div>
</div>
</div>
<script type="text/javascript">
$("#paging_sel").change(function () {
let optVal = $(this).val();
window.location.href = "/cargo/queryList?pageSize=" + optVal;
});
function paginationQuery(pageNum) {
window.location.href = "/cargo/queryList?pageNum=" + pageNum;
}
function toEditAndEditCargo(cargoId) {
window.location.href = "/cargo/toUpdate?cargoId=" + cargoId;
}
function deleteCargoByCargoId(cargoId) {
confirm("你确定要删除该广安防盗门货物吗?") ? window.location.href = "/cargo/deleteCargo?cargoId=" + cargoId : window.location.href = "/cargo/queryList";
}
$(function () {
$("#cargo_add_btn").click(function () {
window.location.href = "/cargo/toSave";
});
})
</script>
</body>
</html>
2.5.8.5、货物前端添加页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>cargo_add</title>
<link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
<script type="text/javascript" th:src="@{/js/jquery-3.6.0.js}"></script>
<script language="javascript" type="text/javascript" th:src="@{/js/My97DatePicker/My97DatePicker/WdatePicker.js}"></script>
<style type="text/css">
#cargo_add_div {
width: 400px;
margin-left: 20px;
margin-top: 20px;
}
</style>
</head>
<body>
<div id="cargo_add_div" class="form-inline">
<form action="/cargo/saveCargo" method="post" id="cargo_add_form">
<div class="form-group">
<label for="cargo_name">货物名称:</label>
<input type="text" class="form-control" name="cargoName" id="cargo_name" placeholder="货物名称">
</div><br><br>
<div class="form-group">
<label for="cargo_units">货物计量单位:</label>
<input type="text" class="form-control" name="cargoUnits" id="cargo_units" placeholder="货物计量单位">
</div><br><br>
<div class="form-group">
<label for="cargo_num">货物数量:</label>
<input type="text" class="form-control" name="cargoNum" id="cargo_num" placeholder="货物数量">
</div><br><br>
<div class="form-group">
<label for="cargo_price">货物价格:</label>
<input type="text" class="form-control" name="cargoPrice" id="cargo_price" placeholder="货物价格">
</div><br><br>
<div class="form-group">
<label for="cargo_manufacturer">生产厂家:</label>
<input type="text" class="form-control" name="cargoManufacturer" id="cargo_manufacturer" placeholder="生产厂家">
</div><br><br>
<div class="form-group">
<label for="category_id">所属分类:</label>
<select name="categoryId" id="category_id">
<option value="">--请选择--</option>
<option th:each="category,index : ${categoryList}" th:value="${category.categoryId}">
<span th:text="${category.categoryName}"></span>
</option>
</select>
</div><br><br>
<div class="form-group">
<label for="cargoWarehouse_entry_time">入库时间:</label>
<input type="text" onClick="WdatePicker({el:this,dateFmt:'yyyy-MM-dd HH:mm:ss'})" class="Wdate form-control" name="cargoWarehouseEntryTime" id="cargoWarehouse_entry_time" placeholder="入库时间">
</div><br><br>
<div class="form-group">
<label for="cargo_operator">操作员:</label>
<input type="text" class="form-control" name="cargoOperator" id="cargo_operator" placeholder="操作员">
</div><br><br>
<button type="submit" class="btn btn-danger btn-sm">保存</button>
</form>
</div>
</body>
</html>
2.5.8.6、货物前端修改页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>cargo_edit</title>
<link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
<script type="text/javascript" th:src="@{/js/jquery-3.6.0.js}"></script>
<script language="javascript" type="text/javascript" th:src="@{/js/My97DatePicker/My97DatePicker/WdatePicker.js}"></script>
<style type="text/css">
#cargo_edit_div {
width: 400px;
margin-left: 20px;
margin-top: 20px;
}
</style>
</head>
<body>
<div id="cargo_edit_div" class="form-inline">
<form action="/cargo/updateCargo" method="post" id="cargo_edit_form">
<input type="hidden" name="cargoId" th:value="${cargo.cargoId}">
<div class="form-group">
<label for="cargo_name">货物名称:</label>
<input type="text" class="form-control" name="cargoName" id="cargo_name" placeholder="货物名称" th:value="${cargo.cargoName}">
</div><br><br>
<div class="form-group">
<label for="cargo_units">货物计量单位:</label>
<input type="text" class="form-control" name="cargoUnits" id="cargo_units" placeholder="货物计量单位" th:value="${cargo.cargoUnits}">
</div><br><br>
<div class="form-group">
<label for="cargo_num">货物数量:</label>
<input type="text" class="form-control" name="cargoNum" id="cargo_num" placeholder="货物数量" th:value="${cargo.cargoNum}">
</div><br><br>
<div class="form-group">
<label for="cargo_price">货物价格:</label>
<input type="text" class="form-control" name="cargoPrice" id="cargo_price" placeholder="货物价格" th:value="${cargo.cargoPrice}">
</div><br><br>
<div class="form-group">
<label for="cargo_manufacturer">生产厂家:</label>
<input type="text" class="form-control" name="cargoManufacturer" id="cargo_manufacturer" placeholder="生产厂家" th:value="${cargo.cargoManufacturer}">
</div><br><br>
<div class="form-group">
<label for="category_id">所属分类:</label>
<select name="categoryId" id="category_id">
<option value="">--请选择--</option>
<option th:each="category,index : ${categoryList}" th:value="${category.categoryId}" th:selected="${category.categoryId == cargo.categoryId}">
<span th:text="${category.categoryName}"></span>
</option>
</select>
</div><br><br>
<div class="form-group">
<label for="cargoWarehouse_entry_time">入库时间:</label>
<input type="text" onClick="WdatePicker({el:this,dateFmt:'yyyy-MM-dd HH:mm:ss'})" class="Wdate form-control" name="cargoWarehouseEntryTime" id="cargoWarehouse_entry_time" placeholder="入库时间" th:value="${cargo.cargoWarehouseEntryTime}">
</div><br><br>
<div class="form-group">
<label for="cargo_operator">操作员:</label>
<input type="text" class="form-control" name="cargoOperator" id="cargo_operator" placeholder="操作员" th:value="${cargo.cargoOperator}">
</div><br><br>
<button type="submit" class="btn btn-danger btn-sm">保存</button>
</form>
</div>
</body>
</html>