基于SSM框架的医院在线挂号预约缴费平台 - 源码深度解析

JavaJavaScriptHTMLCSSSSM框架MySQL
2026-02-0711 浏览

文章摘要

本项目是一款基于SSM(Spring+SpringMVC+MyBatis)框架构建的医院在线服务系统,核心目标是解决传统医院窗口挂号排队耗时、缴费流程繁琐、医疗资源分配不均等痛点。通过将预约、挂号和缴费等核心业务线上化,系统有效分流了线下窗口压力,为患者提供了全天候、一站式的便捷服务,显著提升了就医...

在医疗行业数字化转型的浪潮中,传统医院服务模式正面临巨大挑战。窗口排长队、信息不透明、资源分配不均等问题长期困扰着患者和医院管理者。针对这些痛点,我们设计并实现了一套高效、稳定的医院智慧服务中台,采用成熟的SSM技术栈构建,为医患双方提供全流程的线上服务解决方案。

系统架构与技术栈

该平台采用经典的三层架构设计,充分发挥了SSM框架组合的技术优势。Spring作为核心控制容器,通过依赖注入和面向切面编程管理业务对象的生命周期和事务边界。特别是在挂号、支付等关键业务场景中,Spring的声明式事务管理确保了数据操作的原子性和一致性。

@Service
@Transactional
public class RegistrationService {
    
    @Autowired
    private DoctorScheduleMapper scheduleMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    public String createRegistration(RegistrationDTO dto) {
        // 检查号源状态
        DoctorSchedule schedule = scheduleMapper.selectById(dto.getScheduleId());
        if (schedule.getRemainCount() <= 0) {
            throw new BusinessException("该时段号源已满");
        }
        
        // 创建订单
        Order order = new Order();
        order.setUserId(dto.getUserId());
        order.setScheduleId(dto.getScheduleId());
        order.setStatus(OrderStatus.PENDING_PAYMENT);
        orderMapper.insert(order);
        
        // 更新号源
        schedule.setRemainCount(schedule.getRemainCount() - 1);
        scheduleMapper.updateById(schedule);
        
        return order.getOrderId();
    }
}

SpringMVC负责Web请求的调度和处理,采用RESTful风格的接口设计,使前后端分离更加彻底。控制器层清晰定义了各类业务端点,如挂号预约、订单查询、支付回调等。

@RestController
@RequestMapping("/api/registration")
public class RegistrationController {
    
    @PostMapping("/create")
    public ResponseEntity<ApiResponse> createRegistration(
            @RequestBody @Valid RegistrationDTO dto) {
        try {
            String orderId = registrationService.createRegistration(dto);
            return ResponseEntity.ok(ApiResponse.success(orderId));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(e.getMessage()));
        }
    }
    
    @GetMapping("/list")
    public ResponseEntity<ApiResponse> getRegistrationList(
            @RequestParam String userId,
            @RequestParam(defaultValue = "1") int page) {
        PageInfo<RegistrationVO> pageInfo = registrationService
                .getUserRegistrations(userId, page);
        return ResponseEntity.ok(ApiResponse.success(pageInfo));
    }
}

数据持久层采用MyBatis框架,通过XML映射文件实现复杂的SQL查询和结果集映射。MyBatis的动态SQL特性在处理多条件查询时表现出色,如根据科室、医生、时间等多维度筛选可用号源。

<!-- 医生排班查询映射 -->
<select id="selectAvailableSchedules" resultMap="ScheduleResultMap">
    SELECT s.*, d.name as doctor_name, d.title, dep.name as dept_name
    FROM doctor_schedule s
    LEFT JOIN doctor d ON s.doctor_id = d.doctor_id
    LEFT JOIN department dep ON d.dept_id = dep.dept_id
    WHERE s.schedule_date >= #{startDate}
    <if test="deptId != null">
        AND d.dept_id = #{deptId}
    </if>
    <if test="doctorId != null">
        AND s.doctor_id = #{doctorId}
    </if>
    <if test="timeSlot != null">
        AND s.time_slot = #{timeSlot}
    </if>
    AND s.remain_count > 0
    ORDER BY s.schedule_date, s.time_slot
</select>

数据库设计亮点

套餐业务模块设计

taocan表的设计体现了对医疗套餐业务的深度理解。除了基本的套餐信息外,还包含了丰富的业务字段:

CREATE TABLE `taocan` (
  `taocanid` varchar(255) NOT NULL COMMENT '套餐id',
  `taocanname` varchar(255) DEFAULT NULL COMMENT '套餐名称',
  `image` varchar(255) DEFAULT NULL COMMENT '图片',
  `cateid` varchar(255) DEFAULT NULL COMMENT '分类id',
  `price` varchar(255) DEFAULT NULL COMMENT '价格',
  `recommend` varchar(255) DEFAULT NULL COMMENT '是否推荐',
  `thestart` varchar(255) DEFAULT NULL COMMENT '开始时间',
  `theend` varchar(255) DEFAULT NULL COMMENT '结束时间',
  `hits` varchar(255) DEFAULT NULL COMMENT '点击量',
  `sellnum` varchar(255) DEFAULT NULL COMMENT '销售数量',
  `contents` varchar(6000) DEFAULT NULL COMMENT '内容',
  PRIMARY KEY (`taocanid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT='套餐'

设计亮点分析:

  • 扩展性设计:通过cateid外键关联分类表,支持套餐的多级分类管理
  • 营销功能集成recommend字段支持首页推荐,hitssellnum用于热门排序
  • 时间控制thestarttheend字段实现套餐的有效期管理
  • 内容富文本支持contents字段采用6000字符长度,满足详细说明需求

评论系统的关系设计

topic表构建了用户-套餐的评论关系,支持评分和文字评价:

CREATE TABLE `topic` (
  `topicid` varchar(255) NOT NULL COMMENT '评论id',
  `usersid` varchar(255) DEFAULT NULL COMMENT '用户id',
  `taocanid` varchar(255) DEFAULT NULL COMMENT '套餐id',
  `num` varchar(255) DEFAULT NULL COMMENT '评分',
  `contents` varchar(6000) DEFAULT NULL COMMENT '内容',
  `addtime` varchar(255) DEFAULT NULL COMMENT '添加时间',
  PRIMARY KEY (`topicid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci COMMENT='评论'

索引优化建议:

-- 添加复合索引提升查询性能
CREATE INDEX idx_user_taocan ON topic(usersid, taocanid);
CREATE INDEX idx_taocan_time ON topic(taocanid, addtime DESC);

核心功能实现

智能号源管理

系统实现了智能的号源分配机制,通过可视化管理界面,管理员可以灵活设置医生的出诊排班。

排班管理

后台服务通过复杂的业务逻辑确保号源分配的合理性:

@Service
public class ScheduleManagementService {
    
    public void generateSchedules(GenerateScheduleDTO dto) {
        // 验证时间冲突
        validateScheduleConflict(dto.getDoctorId(), dto.getStartDate(), dto.getEndDate());
        
        List<DoctorSchedule> schedules = new ArrayList<>();
        LocalDate current = dto.getStartDate();
        
        while (!current.isAfter(dto.getEndDate())) {
            if (isWorkDay(current, dto.getDoctorId())) {
                for (String timeSlot : dto.getTimeSlots()) {
                    DoctorSchedule schedule = buildSchedule(dto, current, timeSlot);
                    schedules.add(schedule);
                }
            }
            current = current.plusDays(1);
        }
        
        // 批量插入,提升性能
        batchInsertSchedules(schedules);
    }
    
    private void validateScheduleConflict(String doctorId, 
                                         LocalDate startDate, 
                                         LocalDate endDate) {
        int conflictCount = scheduleMapper.countConflictSchedules(
            doctorId, startDate, endDate);
        if (conflictCount > 0) {
            throw new BusinessException("存在排班时间冲突");
        }
    }
}

在线预约流程

患者可以通过直观的界面查看可预约的号源,并完成在线预约。

提交预约

预约业务逻辑包含完整的校验链条:

@Component
public class RegistrationValidator {
    
    public void validateRegistration(RegistrationDTO dto) {
        // 用户状态校验
        User user = userMapper.selectById(dto.getUserId());
        if (user == null || !user.isActive()) {
            throw new BusinessException("用户状态异常");
        }
        
        // 号源有效性校验
        DoctorSchedule schedule = scheduleMapper.selectById(dto.getScheduleId());
        if (schedule == null || schedule.getRemainCount() <= 0) {
            throw new BusinessException("号源不可用");
        }
        
        // 重复预约校验
        int existingRegistration = registrationMapper
            .countUserRegistrationInPeriod(dto.getUserId(), 
                                         schedule.getScheduleDate());
        if (existingRegistration > 0) {
            throw new BusinessException("同一日期只能预约一次");
        }
        
        // 时间冲突校验
        if (hasTimeConflict(dto.getUserId(), schedule.getScheduleDate())) {
            throw new BusinessException("存在时间冲突的预约");
        }
    }
}

订单支付集成

系统集成了多种支付方式,为患者提供便捷的缴费体验。

订单管理

支付服务采用策略模式支持多种支付渠道:

@Service
public class PaymentService {
    
    @Autowired
    private Map<String, PaymentStrategy> strategies;
    
    public PaymentResult processPayment(PaymentRequest request) {
        PaymentStrategy strategy = strategies.get(request.getPaymentChannel());
        if (strategy == null) {
            throw new BusinessException("不支持的支付方式");
        }
        
        // 验证订单状态
        Order order = orderMapper.selectById(request.getOrderId());
        if (order.getStatus() != OrderStatus.PENDING_PAYMENT) {
            throw new BusinessException("订单状态异常");
        }
        
        // 执行支付
        PaymentResult result = strategy.pay(request);
        
        // 更新订单状态
        if (result.isSuccess()) {
            updateOrderStatus(order.getOrderId(), OrderStatus.PAID);
            sendPaymentSuccessNotification(order.getUserId());
        }
        
        return result;
    }
}

@Component("alipay")
public class AlipayStrategy implements PaymentStrategy {
    
    @Override
    public PaymentResult pay(PaymentRequest request) {
        // 支付宝支付逻辑
        AlipayClient alipayClient = new DefaultAlipayClient(
            alipayConfig.getGateway(),
            alipayConfig.getAppId(),
            alipayConfig.getPrivateKey(),
            "json",
            "UTF-8",
            alipayConfig.getPublicKey(),
            "RSA2");
        
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 设置支付参数...
        
        try {
            String form = alipayClient.pageExecute(alipayRequest).getBody();
            return PaymentResult.success(form);
        } catch (AlipayApiException e) {
            return PaymentResult.fail("支付宝支付失败");
        }
    }
}

管理员综合看板

管理员可以通过功能完善的后台管理系统监控平台运行状态。

用户信息管理

数据统计服务提供多维度的业务洞察:

@Service
public class DashboardService {
    
    public DashboardVO getDashboardData(String adminId) {
        DashboardVO vo = new DashboardVO();
        
        // 今日关键指标
        vo.setTodayRegistrations(registrationMapper.countTodayRegistrations());
        vo.setTodayRevenue(paymentMapper.sumTodayPayments());
        vo.setTodayUsers(userMapper.countTodayNewUsers());
        
        // 预约趋势统计
        vo.setRegistrationTrend(getLast7DaysTrend());
        
        // 热门科室排名
        vo.setPopularDepartments(departmentMapper.getTop5Departments());
        
        // 医生接诊量统计
        vo.setDoctorWorkload(doctorMapper.getDoctorWorkloadStats());
        
        return vo;
    }
    
    private List<TrendData> getLast7DaysTrend() {
        List<TrendData> trend = new ArrayList<>();
        LocalDate today = LocalDate.now();
        
        for (int i = 6; i >= 0; i--) {
            LocalDate date = today.minusDays(i);
            long count = registrationMapper.countByDate(date);
            trend.add(new TrendData(date, count));
        }
        
        return trend;
    }
}

实体模型设计

系统采用规范的实体类设计,每个实体都对应数据库中的表结构。以管理员实体为例:

package com.entity;

import com.util.VeDate;

public class Admin {
    private String adminid = "A" + VeDate.getStringId();
    private String username;
    private String password;
    private String realname;
    private String contact;
    private String addtime;

    public String getAdminid() {
        return adminid;
    }

    public void setAdminid(String adminid) {
        this.adminid = adminid;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRealname() {
        return this.realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    public String getContact() {
        return this.contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    public String getAddtime() {
        return this.addtime;
    }

    public void setAddtime(String addtime) {
        this.addtime = addtime;
    }
}

实体设计采用JavaBean规范,支持灵活的属性访问。ID生成策略采用"前缀+时间戳"的方式,确保唯一性和可读性。

功能展望与优化

分布式架构改造

当前单体架构在业务量增长时可能遇到性能瓶颈。建议引入Spring Cloud微服务架构,将系统拆分为用户服务、预约服务、支付服务等独立模块。

# 建议的微服务配置示例
spring:
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/user/**
        - id: registration-service
          uri: lb://registration-service
          predicates:
            - Path=/api/registration/**

Redis缓存集成

针对高频查询场景,如号源查询、医生信息等,引入Redis缓存大幅提升系统响应速度。

@Service
public class CacheableScheduleService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private static final String SCHEDULE_CACHE_KEY = "schedule:available:";
    
    @Cacheable(value = "schedules", key = "#deptId + ':' + #date")
    public List<ScheduleVO> getAvailableSchedules(String deptId, LocalDate date) {
        // 数据库查询逻辑
        return scheduleMapper.selectAvailableByDeptAndDate(deptId, date);
    }
    
    @CacheEvict(value = "schedules", key = "#deptId + ':' + #date")
    public void evictScheduleCache(String deptId, LocalDate date) {
        // 缓存清除
    }
}

消息队列异步处理

将支付回调、短信通知等非实时业务通过消息队列异步化,提升系统吞吐量。

@Component
public class NotificationService {
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    public void sendPaymentSuccessNotification(String userId, String orderId) {
        PaymentNotification message = new PaymentNotification(userId, orderId);
        rabbitTemplate.convertAndSend("payment.exchange", 
                                    "payment.success", 
                                    message);
    }
}

@Component
public class SMSNotificationListener {
    
    @RabbitListener(queues = "sms.queue")
    public void handlePaymentNotification(PaymentNotification notification) {
        // 发送短信逻辑
        smsService.send(notification.getUserId(), 
                       "预约支付成功提醒");
    }
}

智能推荐引擎

基于用户历史行为数据,构建个性化推荐系统,提升用户体验和资源利用率。

@Service
public class RecommendationService {
    
    public List<Doctor> recommendDoctors(String userId) {
        // 基于协同过滤的推荐算法
        UserPreference preference = analyzeUserBehavior(userId);
        return findSimilarUsersAndRecommend(preference);
    }
    
    private UserPreference analyzeUserBehavior(String userId) {
        // 分析用户历史预约记录、评分等数据
        return userBehaviorAnalyzer.analyze(userId);
    }
}

移动端深度优化

开发专门的移动端应用,支持推送通知、扫码签到、移动支付等便捷功能。

@RestController
@RequestMapping("/api/mobile")
public class MobileRegistrationController {
    
    @PostMapping("/quick-register")
    public ResponseEntity<ApiResponse> quickRegister(
            @RequestParam String qrCode, 
            @RequestParam String userId) {
        // 扫码快速挂号逻辑
        return ResponseEntity.ok(ApiResponse.success("预约成功"));
    }
}

该医院智慧服务中台通过成熟的技术架构和深度的业务理解,为医疗行业的数字化转型提供了可靠的技术支撑。系统在可扩展性、性能优化、用户体验等方面都进行了精心设计,为后续的功能演进和技术升级奠定了坚实基础。随着医疗信息化的深入发展,该平台将持续演进,为构建智慧医院生态发挥更大价值。

本文关键词
SSM框架医院挂号系统在线预约平台源码解析Spring事务管理

上下篇

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