基于SSM的西餐厅物料调配管理系统 - 源码深度解析

JavaJavaScriptHTMLCSSSSM框架MySQL
2026-02-087 浏览

文章摘要

本系统是一款基于SSM(Spring+SpringMVC+MyBatis)框架技术栈开发的西餐厅后台管理软件,旨在解决多门店运营中物料调配与库存管理的核心业务难题。其核心业务价值在于实现了库存信息的集中化、实时化管控,有效解决了传统手工记录或孤立系统导致的库存数据不一致、调配指令延迟、物料浪费与短缺...

连锁西餐厅的运营效率很大程度上取决于物料管理的精细化水平。传统的手工记录或孤立信息系统往往导致库存数据不一致、调配指令延迟、物料浪费与短缺并存等痛点。针对这一行业需求,我们设计并实现了一套基于SSM框架的西餐厅智能物料调配管理平台,通过集中化、实时化的库存管控,有效优化采购决策,降低运营成本,确保各分店高效协同。

系统架构与技术栈

该平台采用经典的SSM三层架构,结合MySQL数据库构建稳定可靠的企业级应用。Spring框架作为核心容器,负责管理所有Bean组件的生命周期与依赖注入,通过声明式事务管理确保库存更新、调配记录写入等关键操作的原子性与数据一致性。

// Spring配置示例
@Configuration
@EnableTransactionManagement
@ComponentScan("com.jly.service")
public class AppConfig {
    
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf-8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setInitialSize(5);
        dataSource.setMaxActive(20);
        return dataSource;
    }
    
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

SpringMVC框架承担Web层职责,通过@Controller注解定义请求处理器,接收并解析前端发起的物料查询、调配申请等HTTP请求。持久层选用MyBatis,通过XML映射文件将Java方法调用与复杂的SQL语句解耦,灵活高效地操作数据库。

数据库设计亮点

商品表设计优化

商品表(smbms_product)的设计体现了对餐饮行业特性的深度理解。除了基本的商品信息外,特别关注了库存管理和食品安全的业务需求。

CREATE TABLE `smbms_product` (
  `id` bigint(20) NOT NULL COMMENT '主键ID',
  `categoryId` bigint(20) DEFAULT NULL COMMENT '分类编号',
  `productName` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品名称',
  `productPhoto` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品图片',
  `primeCost` decimal(10,2) DEFAULT NULL COMMENT '进货价格',
  `salePrice` decimal(10,2) DEFAULT NULL COMMENT '销售价格',
  `quantityStock` int(10) DEFAULT NULL COMMENT '库存数量',
  `quantityWarning` int(10) DEFAULT NULL COMMENT '预警数量',
  `purchasTime` datetime DEFAULT NULL COMMENT '进货时间',
  `productionTtime` datetime DEFAULT NULL COMMENT '生产日期',
  `expirationTime` datetime DEFAULT NULL COMMENT '过期时间',
  `state` int(11) DEFAULT NULL COMMENT '状态(1为上架,2为下架)',
  `barCodePicure` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品条形码',
  `createdBy` bigint(20) DEFAULT NULL COMMENT '创建者(userId)',
  `creationDate` datetime DEFAULT NULL COMMENT '创建时间',
  `modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者(userId)',
  `modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT='商品表'

设计亮点分析:

  • 库存预警机制quantityWarning字段实现智能预警,当库存低于设定阈值时自动提醒补货
  • 全生命周期追踪:通过productionTtimeexpirationTime字段实现食品保质期管理
  • 成本利润控制primeCostsalePrice字段支持精确的成本核算和利润分析
  • 状态管理state字段实现商品的上下架状态控制,避免过期商品流通

商品管理界面

进货订单表业务逻辑设计

进货订单表(smbms_bill)的设计充分考虑了业务流程的完整性和数据一致性。

CREATE TABLE `smbms_bill` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `billCode` varchar(20) DEFAULT NULL COMMENT '订单编码',
  `productName` varchar(20) DEFAULT NULL COMMENT '商品名称',
  `productDesc` varchar(50) DEFAULT NULL COMMENT '订单状态(0:审核中,1:已确认,2:已取消)',
  `productUnit` varchar(10) DEFAULT NULL COMMENT '商品单位',
  `productCount` decimal(20,2) DEFAULT NULL COMMENT '商品数量',
  `totalPrice` decimal(20,2) DEFAULT NULL COMMENT '商品总额',
  `isPayment` int(10) DEFAULT NULL COMMENT '是否支付(1:未支付 2:已支付)',
  `createdBy` bigint(20) DEFAULT NULL COMMENT '创建者(userId)',
  `creationDate` datetime DEFAULT NULL COMMENT '创建时间',
  `modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者(userId)',
  `modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
  `providerId` int(20) DEFAULT NULL COMMENT '供应商ID',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='进货订单表'

业务逻辑设计:

  • 订单状态流转:通过productDesc字段实现订单的审核流程控制
  • 金额精度控制decimal(20,2)类型确保财务计算的精确性
  • 供应商关联providerId字段建立与供应商表的关联关系
  • 操作审计:完整的创建和修改记录支持操作追溯

核心功能实现

订单管理功能

订单管理模块实现了进货订单的全生命周期管理,包括订单查询、添加、修改、删除等核心操作。

@Controller
@RequestMapping("/sys")
public class BillController {

    @Autowired
    private BillService billService;
    @Autowired
    private ProviderService providerService;

    @RequestMapping("/billlist")
    public String findAll(
            @RequestParam(value = "queryProductName", required = false) String proName,
            @RequestParam(value = "queryProviderId", required = false) Integer proid,
            @RequestParam(value = "queryIsPayment", required = false) Integer ispay,
            Model model) {
        List<Bill> billList = billService.findByCondition(proName, proid, ispay);
        List<Provider> providerList = providerService.findAll();
        model.addAttribute("billList", billList);
        model.addAttribute("queryProductName", proName);
        model.addAttribute("queryProviderId", proid);
        model.addAttribute("queryIsPayment", ispay);
        model.addAttribute("providerList", providerList);
        return "billlist";
    }

    @RequestMapping("/addbill.do")
    public String addbill(Bill bill, HttpSession session, Model model) {
        bill.setProductDesc("0"); // 设置初始状态为审核中
        User userSession = (User) session.getAttribute("userSession");
        bill.setCreatedBy(userSession.getId());
        int ret = billService.add(bill);
        if (ret > 0) {
            return "redirect:/sys/billlist";
        } else {
            return "error";
        }
    }
}

对应的MyBatis映射文件实现了复杂的多条件查询逻辑:

<!-- BillMapper.xml -->
<mapper namespace="com.jly.mapper.BillMapper">
    
    <select id="findByCondition" resultType="Bill">
        SELECT b.*, p.proName as providerName 
        FROM smbms_bill b 
        LEFT JOIN smbms_provider p ON b.providerId = p.id
        <where>
            <if test="productName != null and productName != ''">
                AND b.productName LIKE CONCAT('%', #{productName}, '%')
            </if>
            <if test="providerId != null">
                AND b.providerId = #{providerId}
            </if>
            <if test="isPayment != null">
                AND b.isPayment = #{isPayment}
            </if>
        </where>
        ORDER BY b.creationDate DESC
    </select>
    
    <insert id="add" parameterType="Bill" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO smbms_bill 
        (billCode, productName, productDesc, productUnit, productCount, 
         totalPrice, isPayment, createdBy, creationDate, providerId)
        VALUES 
        (#{billCode}, #{productName}, #{productDesc}, #{productUnit}, #{productCount},
         #{totalPrice}, #{isPayment}, #{createdBy}, NOW(), #{providerId})
    </insert>
</mapper>

采购管理界面

库存预警与自动提醒

系统通过定时任务监控库存状态,当商品库存低于预警线时自动触发提醒机制。

@Service
public class InventoryWarningService {
    
    @Autowired
    private ProductService productService;
    @Autowired
    private EmailService emailService;
    
    @Scheduled(cron = "0 0 8 * * ?") // 每天上午8点执行
    public void checkInventoryWarning() {
        List<Product> warningProducts = productService.findLowStockProducts();
        
        if (!warningProducts.isEmpty()) {
            StringBuilder message = new StringBuilder();
            message.append("以下商品库存低于预警线,请及时补货:\n\n");
            
            for (Product product : warningProducts) {
                message.append(String.format("商品名称:%s,当前库存:%d,预警数量:%d\n", 
                    product.getProductName(), 
                    product.getQuantityStock(), 
                    product.getQuantityWarning()));
            }
            
            emailService.sendWarningEmail("inventory@restaurant.com", 
                "库存预警提醒", message.toString());
        }
    }
}

供应商管理功能

供应商管理模块实现了供应商信息的维护和评估功能,支持多条件查询和分页显示。

@Service
public class ProviderServiceImpl implements ProviderService {
    
    @Autowired
    private ProviderMapper providerMapper;
    
    @Override
    public List<Provider> findByCondition(String proCode, String proName) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.isNotBlank(proCode)) {
            params.put("proCode", proCode);
        }
        if (StringUtils.isNotBlank(proName)) {
            params.put("proName", proName);
        }
        return providerMapper.selectByCondition(params);
    }
    
    @Override
    @Transactional
    public int addProvider(Provider provider) {
        // 检查供应商编码是否重复
        Provider existProvider = providerMapper.selectByCode(provider.getProCode());
        if (existProvider != null) {
            throw new BusinessException("供应商编码已存在");
        }
        return providerMapper.insert(provider);
    }
}

供应商管理界面

实体模型设计

系统采用面向对象的设计思想,实体类与数据库表严格对应,并通过注解实现ORM映射。

// 商品实体类
public class Product {
    private Long id;
    private Long categoryId;
    private String productName;
    private String productPhoto;
    private BigDecimal primeCost;
    private BigDecimal salePrice;
    private Integer quantityStock;
    private Integer quantityWarning;
    private Date purchasTime;
    private Date productionTtime;
    private Date expirationTime;
    private Integer state;
    private String barCodePicure;
    private Long createdBy;
    private Date creationDate;
    private Long modifyBy;
    private Date modifyDate;
    
    // 构造函数、getter、setter方法
    public Product() {}
    
    public boolean isLowStock() {
        return quantityStock != null && quantityWarning != null 
               && quantityStock < quantityWarning;
    }
    
    public boolean isExpired() {
        return expirationTime != null && expirationTime.before(new Date());
    }
}
// 订单实体类
public class Bill {
    private Long id;
    private String billCode;
    private String productName;
    private String productDesc;
    private String productUnit;
    private BigDecimal productCount;
    private BigDecimal totalPrice;
    private Integer isPayment;
    private Long createdBy;
    private Date creationDate;
    private Long modifyBy;
    private Date modifyDate;
    private Long providerId;
    private String providerName; // 关联查询字段
    
    // 业务方法
    public BigDecimal calculateTotalPrice() {
        if (productCount != null && primeCost != null) {
            return productCount.multiply(primeCost);
        }
        return BigDecimal.ZERO;
    }
}

功能展望与优化

1. 引入Redis缓存提升性能

当前系统在高并发场景下可能存在数据库压力问题。通过引入Redis缓存,可以显著提升系统性能。

@Service
public class ProductServiceWithCache {
    
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String PRODUCT_CACHE_KEY = "product:";
    private static final long CACHE_EXPIRE_TIME = 3600; // 1小时
    
    public Product findById(Long id) {
        String cacheKey = PRODUCT_CACHE_KEY + id;
        Product product = (Product) redisTemplate.opsForValue().get(cacheKey);
        
        if (product == null) {
            product = productMapper.selectById(id);
            if (product != null) {
                redisTemplate.opsForValue().set(cacheKey, product, 
                    CACHE_EXPIRE_TIME, TimeUnit.SECONDS);
            }
        }
        return product;
    }
    
    @CacheEvict(key = "'product:' + #product.id")
    public void updateProduct(Product product) {
        productMapper.update(product);
    }
}

2. 消息队列实现异步处理

对于库存更新、邮件发送等耗时操作,可以通过消息队列实现异步处理,提升系统响应速度。

@Component
public class InventoryMessageProducer {
    
    @Autowired
    private AmqpTemplate rabbitTemplate;
    
    public void sendInventoryUpdate(InventoryUpdateMessage message) {
        rabbitTemplate.convertAndSend("inventory.exchange", 
            "inventory.update", message);
    }
}

@Component
public class InventoryMessageConsumer {
    
    @RabbitListener(queues = "inventory.queue")
    public void processInventoryUpdate(InventoryUpdateMessage message) {
        // 异步处理库存更新逻辑
        inventoryService.updateStock(message.getProductId(), 
            message.getQuantity(), message.getOperationType());
    }
}

3. 微服务架构改造

随着业务规模扩大,可以将单体应用拆分为微服务架构,提高系统的可扩展性和维护性。

# 微服务配置示例
spring:
  application:
    name: inventory-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080

server:
  port: 8081

# 库存服务配置
inventory:
  warning:
    enabled: true
    threshold: 50

4. 移动端适配与PWA技术

开发移动端应用,支持餐厅员工通过手机进行库存盘点、调配申请等操作。

// 移动端库存管理示例
class MobileInventoryApp {
    constructor() {
        this.initServiceWorker();
        this.bindEvents();
    }
    
    initServiceWorker() {
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js')
                .then(registration => {
                    console.log('SW registered: ', registration);
                });
        }
    }
    
    async checkInventory() {
        try {
            const response = await fetch('/api/inventory/current');
            const inventory = await response.json();
            this.displayInventory(inventory);
        } catch (error) {
            this.showOfflineMessage();
        }
    }
}

5. 智能预测与AI优化

引入机器学习算法,基于历史销售数据预测未来需求,实现智能补货建议。

# 需求预测模型示例
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split

class DemandPredictor:
    def __init__(self):
        self.model = RandomForestRegressor(n_estimators=100)
    
    def train(self, historical_data):
        # 特征工程:日期、季节、促销活动等
        features = self.extract_features(historical_data)
        targets = historical_data['sales_quantity']
        
        X_train, X_test, y_train, y_test = train_test_split(
            features, targets, test_size=0.2)
        
        self.model.fit(X_train, y_train)
        return self.model.score(X_test, y_test)
    
    def predict_demand(self, product_id, days_ahead=7):
        # 基于历史数据预测未来需求
        future_features = self.prepare_future_features(days_ahead)
        return self.model.predict(future_features)

总结

西餐厅智能物料调配管理平台通过SSM框架的稳健架构,结合精细化的数据库设计,实现了物料管理的数字化转型升级。系统在订单管理、库存预警、供应商协同等核心业务场景中表现出色,为连锁西餐厅的规模化运营提供了坚实的技术支撑。

系统登录界面

未来通过引入缓存优化、消息队列、微服务架构等先进技术,可以进一步提升系统的性能、可扩展性和智能化水平。特别是在AI预测、移动端适配等方面的优化,将为餐厅运营带来更大的价值提升。该平台的架构设计和实现方案为餐饮行业的数字化转型提供了可借鉴的实践范例。

本文关键词
SSM框架西餐厅管理物料调配系统库存管理数据库设计

上下篇

上一篇
没有更多文章
下一篇
没有更多文章