SpringBoot怎么实现点餐小程序

发布时间:2022-07-16 13:57:31 作者:iii
来源:亿速云 阅读:106

SpringBoot怎么实现点餐小程序

目录

  1. 引言
  2. 项目需求分析
  3. 技术选型
  4. 项目结构设计
  5. 数据库设计
  6. SpringBoot项目搭建
  7. 用户模块实现
  8. 菜品模块实现
  9. 订单模块实现
  10. 支付模块实现
  11. 小程序前端开发
  12. 前后端联调
  13. 项目部署
  14. 总结

引言

随着移动互联网的快速发展,点餐小程序成为了餐饮行业的重要工具。通过点餐小程序,用户可以方便地浏览菜单、下单、支付,而商家则可以高效地管理订单、库存等。本文将详细介绍如何使用SpringBoot实现一个点餐小程序的后端服务,并结合小程序前端开发,完成一个完整的点餐系统。

项目需求分析

在开始开发之前,我们需要明确项目的需求。一个典型的点餐小程序通常包括以下功能:

  1. 用户管理:用户注册、登录、个人信息管理。
  2. 菜品管理:菜品分类、菜品详情、菜品搜索。
  3. 订单管理:下单、订单查询、订单状态更新。
  4. 支付功能:支持微信支付、支付宝支付等。
  5. 后台管理:商家可以管理菜品、订单、库存等。

技术选型

为了实现上述功能,我们需要选择合适的技术栈:

项目结构设计

一个典型的SpringBoot项目结构如下:

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           └── order
│   │               ├── config
│   │               ├── controller
│   │               ├── dao
│   │               ├── entity
│   │               ├── service
│   │               └── OrderApplication.java
│   └── resources
│       ├── application.properties
│       ├── static
│       └── templates
└── test
    └── java
        └── com
            └── example
                └── order

数据库设计

根据需求,我们需要设计以下数据库表:

  1. 用户表(user)

    • id
    • username
    • password
    • phone
    • create_time
  2. 菜品表(dish)

    • id
    • name
    • price
    • description
    • category_id
    • create_time
  3. 订单表(order)

    • id
    • user_id
    • total_price
    • status
    • create_time
  4. 订单详情表(order_detail)

    • id
    • order_id
    • dish_id
    • quantity
    • price
  5. 支付表(payment)

    • id
    • order_id
    • payment_method
    • amount
    • status
    • create_time

SpringBoot项目搭建

首先,我们需要创建一个SpringBoot项目。可以使用Spring Initializr快速生成项目骨架。

  1. 打开Spring Initializr
  2. 选择Maven项目,语言选择Java,Spring Boot版本选择最新稳定版。
  3. 添加依赖:Spring Web、Spring Data JPA、MySQL Driver、Lombok、Spring Boot DevTools。
  4. 点击生成并下载项目。

解压下载的项目,导入到IDE中(如IntelliJ IDEA)。

用户模块实现

用户实体类

package com.example.order.entity;

import lombok.Data;
import javax.persistence.*;
import java.util.Date;

@Data
@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;
    private String password;
    private String phone;

    @Column(name = "create_time")
    private Date createTime;
}

用户Repository

package com.example.order.dao;

import com.example.order.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {
    User findByUsername(String username);
}

用户Service

package com.example.order.service;

import com.example.order.entity.User;
import com.example.order.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public User register(User user) {
        user.setCreateTime(new Date());
        return userRepository.save(user);
    }

    public User login(String username, String password) {
        return userRepository.findByUsernameAndPassword(username, password);
    }
}

用户Controller

package com.example.order.controller;

import com.example.order.entity.User;
import com.example.order.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public User register(@RequestBody User user) {
        return userService.register(user);
    }

    @PostMapping("/login")
    public User login(@RequestParam String username, @RequestParam String password) {
        return userService.login(username, password);
    }
}

菜品模块实现

菜品实体类

package com.example.order.entity;

import lombok.Data;
import javax.persistence.*;
import java.util.Date;

@Data
@Entity
@Table(name = "dish")
public class Dish {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private Double price;
    private String description;

    @Column(name = "category_id")
    private Long categoryId;

    @Column(name = "create_time")
    private Date createTime;
}

菜品Repository

package com.example.order.dao;

import com.example.order.entity.Dish;
import org.springframework.data.jpa.repository.JpaRepository;

public interface DishRepository extends JpaRepository<Dish, Long> {
}

菜品Service

package com.example.order.service;

import com.example.order.entity.Dish;
import com.example.order.dao.DishRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishService {
    @Autowired
    private DishRepository dishRepository;

    public List<Dish> getAllDishes() {
        return dishRepository.findAll();
    }

    public Dish getDishById(Long id) {
        return dishRepository.findById(id).orElse(null);
    }

    public Dish addDish(Dish dish) {
        dish.setCreateTime(new Date());
        return dishRepository.save(dish);
    }
}

菜品Controller

package com.example.order.controller;

import com.example.order.entity.Dish;
import com.example.order.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @GetMapping("/list")
    public List<Dish> getAllDishes() {
        return dishService.getAllDishes();
    }

    @GetMapping("/{id}")
    public Dish getDishById(@PathVariable Long id) {
        return dishService.getDishById(id);
    }

    @PostMapping("/add")
    public Dish addDish(@RequestBody Dish dish) {
        return dishService.addDish(dish);
    }
}

订单模块实现

订单实体类

package com.example.order.entity;

import lombok.Data;
import javax.persistence.*;
import java.util.Date;
import java.util.List;

@Data
@Entity
@Table(name = "order")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "user_id")
    private Long userId;

    @Column(name = "total_price")
    private Double totalPrice;

    private String status;

    @Column(name = "create_time")
    private Date createTime;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<OrderDetail> orderDetails;
}

订单详情实体类

package com.example.order.entity;

import lombok.Data;
import javax.persistence.*;

@Data
@Entity
@Table(name = "order_detail")
public class OrderDetail {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "order_id")
    private Long orderId;

    @Column(name = "dish_id")
    private Long dishId;

    private Integer quantity;
    private Double price;

    @ManyToOne
    @JoinColumn(name = "order_id", insertable = false, updatable = false)
    private Order order;
}

订单Repository

package com.example.order.dao;

import com.example.order.entity.Order;
import org.springframework.data.jpa.repository.JpaRepository;

public interface OrderRepository extends JpaRepository<Order, Long> {
}

订单Service

package com.example.order.service;

import com.example.order.entity.Order;
import com.example.order.dao.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    public Order createOrder(Order order) {
        order.setCreateTime(new Date());
        return orderRepository.save(order);
    }

    public List<Order> getOrdersByUserId(Long userId) {
        return orderRepository.findByUserId(userId);
    }

    public Order updateOrderStatus(Long orderId, String status) {
        Order order = orderRepository.findById(orderId).orElse(null);
        if (order != null) {
            order.setStatus(status);
            return orderRepository.save(order);
        }
        return null;
    }
}

订单Controller

package com.example.order.controller;

import com.example.order.entity.Order;
import com.example.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public Order createOrder(@RequestBody Order order) {
        return orderService.createOrder(order);
    }

    @GetMapping("/user/{userId}")
    public List<Order> getOrdersByUserId(@PathVariable Long userId) {
        return orderService.getOrdersByUserId(userId);
    }

    @PutMapping("/{orderId}/status")
    public Order updateOrderStatus(@PathVariable Long orderId, @RequestParam String status) {
        return orderService.updateOrderStatus(orderId, status);
    }
}

支付模块实现

支付实体类

package com.example.order.entity;

import lombok.Data;
import javax.persistence.*;
import java.util.Date;

@Data
@Entity
@Table(name = "payment")
public class Payment {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "order_id")
    private Long orderId;

    @Column(name = "payment_method")
    private String paymentMethod;

    private Double amount;
    private String status;

    @Column(name = "create_time")
    private Date createTime;
}

支付Repository

package com.example.order.dao;

import com.example.order.entity.Payment;
import org.springframework.data.jpa.repository.JpaRepository;

public interface PaymentRepository extends JpaRepository<Payment, Long> {
}

支付Service

package com.example.order.service;

import com.example.order.entity.Payment;
import com.example.order.dao.PaymentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class PaymentService {
    @Autowired
    private PaymentRepository paymentRepository;

    public Payment createPayment(Payment payment) {
        payment.setCreateTime(new Date());
        return paymentRepository.save(payment);
    }

    public Payment updatePaymentStatus(Long paymentId, String status) {
        Payment payment = paymentRepository.findById(paymentId).orElse(null);
        if (payment != null) {
            payment.setStatus(status);
            return paymentRepository.save(payment);
        }
        return null;
    }
}

支付Controller

package com.example.order.controller;

import com.example.order.entity.Payment;
import com.example.order.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/payment")
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @PostMapping("/create")
    public Payment createPayment(@RequestBody Payment payment) {
        return paymentService.createPayment(payment);
    }

    @PutMapping("/{paymentId}/status")
    public Payment updatePaymentStatus(@PathVariable Long paymentId, @RequestParam String status) {
        return paymentService.updatePaymentStatus(paymentId, status);
    }
}

小程序前端开发

项目结构

miniprogram
├── app.js
├── app.json
├── app.wxss
├── pages
│   ├── index
│   │   ├── index.js
│   │   ├── index.json
│   │   ├── index.wxml
│   │   └── index.wxss
│   ├── user
│   │   ├── user.js
│   │   ├── user.json
│   │   ├── user.wxml
│   │   └── user.wxss
│   ├── dish
│   │   ├── dish.js
│   │   ├── dish.json
│   │   ├── dish.wxml
│   │   └── dish.wxss
│   └── order
│       ├── order.js
│       ├── order.json
│       ├── order.wxml
│       └── order.wxss
└── utils
    └── request.js

首页(index)

<!-- index.wxml -->
<view class="container">
    <view class="header">
        <text>欢迎使用点餐小程序</text>
    </view>
    <view class="menu">
        <navigator url="/pages/dish/dish">菜品列表</navigator>
        <navigator url="/pages/order/order">我的订单</navigator>
        <navigator url="/pages/user/user">个人中心</navigator>
    </view>
</view>

菜品列表页(dish)

<!-- dish.wxml -->
<view class="container">
    <view class="header">
        <text>菜品列表</text>
    </view>
    <view class="dish-list">
        <block wx:for="{{dishList}}" wx:key="id">
            <view class="dish-item">
                <text>{{item.name}}</text>
                <text>价格:{{item.price}}元</text>
                <button bindtap="addToCart" data-id="{{item.id}}">加入购物车</button>
            </view>
        </block>
    </view>
</view>
// dish.js
Page({
    data: {
        dishList: []
    },
    onLoad: function () {
        this.getDishList();
    },
    getDishList: function () {
        wx.request({
            url: 'http://localhost:8080/dish/list',
            method: 'GET',
            success: (res) => {
                this.setData({
                    dishList: res.data
                });
            }
        });
    },
    addToCart: function (e) {
        const dishId = e.currentTarget.dataset.id;
        wx.request({
            url: 'http://localhost:8080/order/create',
            method: 'POST',
            data: {
                userId: 1, // 假设用户ID为1
                dishId: dishId,
                quantity: 1
            },
            success: (res) => {
                wx.showToast({
                    title: '加入购物车成功',
                    icon: 'success'
                });
            }
        });
    }
});

订单页(order)

<!-- order.wxml -->
<view class="container">
    <view class="header">
        <text>我的订单</text>
    </view>
    <view class="order-list">
        <block wx:for="{{orderList}}" wx:key="id">
            <view class="order-item">
                <text>订单号:{{item.id}}</text>
                <text>总价:{{item.totalPrice}}元</text>
                <text>状态:{{item.status}}</text>
            </view>
        </block>
    </view>
</view>
// order.js
Page({
    data: {
        orderList: []
    },
    onLoad: function () {
        this.getOrderList();
    },
    getOrderList: function () {
        wx.request({
            url: 'http://localhost:8080/order/user/1', // 假设用户ID为1
            method: 'GET',
            success: (res) => {
                this.setData({
                    orderList: res.data
                });
            }
        });
    }
});

个人中心页(user)

<!-- user.wxml -->
<view class="container">
    <view class="header">
        <text>个人中心</text>
    </view>
    <view class="user-info">
        <text>用户名:{{userInfo.username}}</text>
        <text>手机号:{{userInfo.phone}}</text>
    </view>
</view>
// user.js
Page({
    data: {
        userInfo: {}
    },
    onLoad: function () {
        this.getUserInfo();
    },
    getUserInfo: function () {
        wx.request({
            url: 'http://localhost:8080/user/1', // 假设用户ID为1
            method: 'GET',
            success: (res) => {
                this.setData({
                    userInfo: res.data
                });
            }
        });
    }
});

前后端联调

在开发过程中,前后端需要进行联调以确保接口的正确性和数据的准确性。可以使用Postman等工具进行接口测试,确保后端接口能够正确处理请求并返回预期的结果。

项目部署

后端部署

  1. 打包Spring
推荐阅读:
  1. 使用JavaScript怎么编写一个点餐小程序
  2. 微信小程序中实现点餐系统常见问题有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot

上一篇:pandas中的Timestamp只保留日期不显示时间怎么实现

下一篇:linux中acpi指的是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》