基于SpringBoot的建材在线选购与交易平台 - 源码深度解析
随着建筑行业数字化转型的加速,传统建材采购模式面临诸多挑战:信息不对称、供应链冗长、交易效率低下等问题日益凸显。针对这些行业痛点,我们设计并实现了一个现代化的建材电商平台,该平台采用SpringBoot作为核心框架,整合了完整的电商功能模块,为建筑企业、装修公司及个人用户提供高效的在线选购与交易服务。
系统架构与技术栈
该平台采用典型的分层架构设计,前端使用Thymeleaf模板引擎结合Bootstrap组件库构建响应式用户界面,后端基于SpringBoot框架实现业务逻辑处理。数据持久层采用Spring Data JPA与MySQL数据库进行交互,确保了数据操作的简洁性和一致性。
在技术选型上,平台充分利用了SpringBoot的自动化配置特性,显著简化了项目初始化和部署流程。关键配置如下:
# 数据库连接配置
spring:
datasource:
url: jdbc:mysql://www.csbishe.cn/boot_jiancaishop?useSSL=false&serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true
username: boot_jiancaishop
password: boot_jiancaishop
driver-class-name: com.mysql.cj.jdbc.Driver
# 连接池优化配置
dbcp2:
max-wait-millis: 10000
min-idle: 5
initial-size: 5
# 文件上传限制
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
技术栈深度解析:
- SpringBoot 2.x:采用约定优于配置的理念,内置Tomcat服务器,简化Maven配置
- Spring Data JPA:基于Hibernate实现ORM映射,支持方法名查询和@Query注解
- MySQL 8.0:支持事务ACID特性,采用InnoDB存储引擎确保数据一致性
- Thymeleaf 3.0:天然支持HTML5,与SpringBoot完美集成,支持模板片段复用
数据库设计亮点分析
商品表设计优化
商品表(goods)的设计体现了电商系统的核心数据模型,采用多维度字段满足业务需求:
CREATE TABLE `goods` (
`goods_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '商品ID',
`goods_type_id` int(11) DEFAULT 0 COMMENT '商品类型ID',
`goods_no` varchar(50) DEFAULT NULL COMMENT '商品编号',
`goods_name` varchar(225) DEFAULT NULL COMMENT '商品名称',
`goods_pic` varchar(225) DEFAULT NULL COMMENT '商品图片',
`goods_publisher` varchar(225) DEFAULT NULL COMMENT '发布者',
`goods_price` double DEFAULT 0 COMMENT '商品价格',
`goods_discount` double DEFAULT NULL COMMENT '商品折扣',
`goods_date` varchar(50) DEFAULT NULL COMMENT '上架日期',
`goods_desc` text DEFAULT NULL COMMENT '商品描述',
`goods_ban` int(11) DEFAULT NULL COMMENT '是否禁售',
PRIMARY KEY (`goods_id`) USING BTREE,
KEY `idx_goods_type` (`goods_type_id`),
KEY `idx_goods_name` (`goods_name`(20))
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci ROW_FORMAT=DYNAMIC COMMENT='商品表';
表设计核心技术亮点:
- 索引策略优化:除主键索引外,针对商品类型和名称建立复合索引,提升查询性能
- 存储引擎选择:采用InnoDB支持行级锁和事务处理,确保高并发下的数据一致性
- 字段设计规范:商品描述使用TEXT类型,支持大文本存储;价格字段采用DOUBLE确保精度
- 业务状态管理:通过goods_ban字段实现商品软删除,避免物理删除导致的数据丢失
购物车表业务逻辑设计
购物车表(gouwuche)的设计充分考虑用户购物体验和并发处理:
CREATE TABLE `gouwuche` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '购物车ID',
`goods_id` int(11) DEFAULT NULL COMMENT '商品ID',
`user_id` int(11) DEFAULT NULL COMMENT '用户ID',
`time` date DEFAULT NULL COMMENT '添加时间',
`count` int(11) NOT NULL DEFAULT 1 COMMENT '商品数量',
PRIMARY KEY (`id`),
KEY `idx_user_goods` (`user_id`,`goods_id`),
CONSTRAINT `fk_cart_goods` FOREIGN KEY (`goods_id`) REFERENCES `goods` (`goods_id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=159 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='购物车表';
高级设计特性:
- 外键约束优化:建立goods_id外键约束,确保数据引用完整性
- 联合索引设计:通过(user_id, goods_id)联合索引优化购物车查询性能
- 默认值策略:count字段默认值为1,符合用户购物习惯
- 时间维度管理:time字段采用DATE类型,支持按天统计和过期数据清理

核心功能实现深度解析
商品管理模块
商品管理采用Repository模式实现数据访问层,结合Specification动态查询构建复杂业务逻辑:
@Service
@Transactional(readOnly = true)
public class GoodsService {
@Autowired
private GoodsRepository goodsRepository;
/**
* 动态条件查询商品列表
* 支持商品名称模糊查询和商品类型精确匹配
*/
public Page<Goods> findGoodsByCriteria(GoodsQuery query, Pageable pageable) {
Specification<Goods> spec = (root, criteriaQuery, criteriaBuilder) -> {
List<Predicate> predicates = new ArrayList<>();
// 商品名称模糊查询
if (StringUtils.hasText(query.getGoodsName())) {
predicates.add(criteriaBuilder.like(root.get("goodsName"),
"%" + query.getGoodsName() + "%"));
}
// 商品类型精确匹配
if (query.getGoodsTypeId() != null) {
predicates.add(criteriaBuilder.equal(root.get("goodsTypeId"),
query.getGoodsTypeId()));
}
// 商品状态过滤
predicates.add(criteriaBuilder.equal(root.get("goodsBan"), 0));
return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
};
return goodsRepository.findAll(spec, pageable);
}
/**
* 更新商品状态 - 采用声明式事务管理
*/
@Transactional
public void updateGoodsStatus(Integer goodsId, Integer status) {
Goods goods = goodsRepository.findById(goodsId)
.orElseThrow(() -> new BusinessException("商品不存在"));
goods.setGoodsBan(status);
goodsRepository.save(goods);
}
/**
* 批量更新商品价格
*/
@Transactional
public int batchUpdatePrice(List<Integer> goodsIds, Double newPrice) {
return goodsRepository.batchUpdatePrice(goodsIds, newPrice);
}
}

订单处理系统
订单模块采用DDD领域驱动设计思想,通过Service层封装复杂业务逻辑:
@RestController
@RequestMapping("/api/orders")
@Validated
public class OrderController {
@Autowired
private OrderService orderService;
/**
* 创建订单 - 采用声明式事务确保数据一致性
* 包含库存校验、价格计算、订单生成等原子操作
*/
@PostMapping("/create")
@Transactional(rollbackFor = Exception.class)
public ResponseEntity<ApiResponse<OrderDTO>> createOrder(
@Valid @RequestBody OrderRequest request) {
try {
OrderDTO order = orderService.createOrder(request);
return ResponseEntity.ok(ApiResponse.success(order));
} catch (InsufficientStockException e) {
log.warn("库存不足: {}", e.getMessage());
return ResponseEntity.badRequest()
.body(ApiResponse.error("库存不足"));
} catch (BusinessException e) {
log.error("业务异常: {}", e.getMessage());
return ResponseEntity.badRequest()
.body(ApiResponse.error(e.getMessage()));
}
}
/**
* 分页查询用户订单
*/
@GetMapping("/user/{userId}")
public ResponseEntity<ApiResponse<Page<OrderDTO>>> getUserOrders(
@PathVariable @Min(1) Integer userId,
@PageableDefault(size = 10, sort = "createTime",
direction = Direction.DESC) Pageable pageable) {
Page<OrderDTO> orders = orderService.findOrdersByUserId(userId, pageable);
return ResponseEntity.ok(ApiResponse.success(orders));
}
}
订单表核心设计:
CREATE TABLE `dingdan` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '订单ID',
`order_no` varchar(32) NOT NULL COMMENT '订单编号',
`user_id` int(11) NOT NULL COMMENT '用户ID',
`total_amount` decimal(10,2) NOT NULL COMMENT '订单总金额',
`status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '订单状态',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_order_no` (`order_no`),
KEY `idx_user_status` (`user_id`,`status`),
KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单主表';
系统性能优化策略:
- 数据库连接池配置连接超时和最小空闲连接数
- 采用分页查询避免大数据量查询导致的性能问题
- 使用@Transactional注解管理事务边界
- 通过索引优化提升查询性能