溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot怎么實現點餐小程序

發布時間:2022-07-16 13:57:31 來源:億速云 閱讀:118 作者:iii 欄目:開發技術

SpringBoot怎么實現點餐小程序

目錄

  1. 引言
  2. 項目需求分析
  3. 技術選型
  4. 項目結構設計
  5. 數據庫設計
  6. SpringBoot項目搭建
  7. 用戶模塊實現
  8. 菜品模塊實現
  9. 訂單模塊實現
  10. 支付模塊實現
  11. 小程序前端開發
  12. 前后端聯調
  13. 項目部署
  14. 總結

引言

隨著移動互聯網的快速發展,點餐小程序成為了餐飲行業的重要工具。通過點餐小程序,用戶可以方便地瀏覽菜單、下單、支付,而商家則可以高效地管理訂單、庫存等。本文將詳細介紹如何使用SpringBoot實現一個點餐小程序的后端服務,并結合小程序前端開發,完成一個完整的點餐系統。

項目需求分析

在開始開發之前,我們需要明確項目的需求。一個典型的點餐小程序通常包括以下功能:

  1. 用戶管理:用戶注冊、登錄、個人信息管理。
  2. 菜品管理:菜品分類、菜品詳情、菜品搜索。
  3. 訂單管理:下單、訂單查詢、訂單狀態更新。
  4. 支付功能:支持微信支付、支付寶支付等。
  5. 后臺管理:商家可以管理菜品、訂單、庫存等。

技術選型

為了實現上述功能,我們需要選擇合適的技術棧:

  • 后端框架:SpringBoot
  • 數據庫MySQL
  • 緩存Redis
  • 消息隊列:RabbitMQ
  • 前端框架:微信小程序
  • 支付接口:微信支付、支付寶支付

項目結構設計

一個典型的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項目??梢允褂肧pring 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
                });
            }
        });
    }
});

前后端聯調

在開發過程中,前后端需要進行聯調以確保接口的正確性和數據的準確性??梢允褂肞ostman等工具進行接口測試,確保后端接口能夠正確處理請求并返回預期的結果。

項目部署

后端部署

  1. 打包Spring
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女