LMT 3 months ago
commit 1fced146c8

@ -0,0 +1,2 @@
# mallsystem

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<!-- 编译器配置组件 -->
<component name="CompilerConfiguration">
<!-- 注解处理配置 -->
<annotationProcessing>
<!-- Maven 默认注解处理器配置 -->
<profile name="Maven default annotation processors profile" enabled="true">
<!-- 生成的源代码输出目录 -->
<sourceOutputDir name="target/generated-sources/annotations" />
<!-- 生成的测试源代码输出目录 -->
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<!-- 输出路径相对于内容根目录 -->
<outputRelativeToContentRoot value="true" />
<!-- 应用此配置的模块名称 -->
<module name="springboot" />
</profile>
</annotationProcessing>
</component>
<!-- Java 编译器设置 -->
<component name="JavacSettings">
<!-- 附加编译器选项覆盖 -->
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<!-- 为名为 "springboot" 的模块指定编译器选项 -->
<module name="springboot" options="-parameters" />
</option>
</component>
</project>

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<!-- 文件编码设置组件 -->
<component name="Encoding">
<!--
设置项目目录的编码格式
url: 项目目录路径,$PROJECT_DIR$ 是项目根目录的变量引用
charset: 文件编码格式UTF-8 确保支持多语言字符
-->
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
</component>
</project>

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
IntelliJ IDEA 远程仓库配置文件
文件:.idea/remote-repositories.xml
版本4
用途配置Maven远程仓库地址用于项目依赖下载
-->
<project version="4">
<!-- 远程仓库配置组件 -->
<component name="RemoteRepositoriesConfiguration">
<!-- 阿里云Nexus仓库HTTPS -->
<remote-repository>
<option name="id" value="public" />
<option name="name" value="aliyun nexus" />
<option name="url" value="https://maven.aliyun.com/repository/public" />
</remote-repository>
<!-- Maven中央仓库Apache官方 -->
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<!-- 阿里云Nexus仓库HTTP -->
<remote-repository>
<option name="id" value="public" />
<option name="name" value="aliyun nexus" />
<option name="url" value="http://maven.aliyun.com/nexus/content/groups/public/" />
</remote-repository>
<!-- Maven中央仓库官方备用地址 -->
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<!-- JBoss社区仓库 -->
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<!-- 阿里云仓库(再次配置,可能作为主要仓库) -->
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://maven.aliyun.com/repository/public" />
</remote-repository>
</component>
</project>

@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
IntelliJ IDEA 项目杂项配置文件
文件:.idea/misc.xml
版本4
用途:存储项目的各种基础配置信息
-->
<project version="4">
<!--
外部存储配置管理器
enabled="true" 表示启用对外部存储设备的支持
允许项目存储在外部硬盘、网络驱动器等位置
-->
<component name="ExternalStorageConfigurationManager" enabled="true" />
<!--
Maven项目管理器配置
负责管理Maven项目的构建和依赖关系
-->
<component name="MavenProjectsManager">
<!--
原始Maven配置文件列表
指定项目使用的Maven构建配置文件
-->
<option name="originalFiles">
<list>
<!--
项目根目录下的pom.xml文件
$PROJECT_DIR$ 是IDEA内置变量自动指向当前项目根目录的绝对路径
-->
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<!--
项目根管理器配置
这是项目的核心配置定义了项目的Java环境设置
-->
<component name="ProjectRootManager" version="2"
languageLevel="JDK_1_8"
default="true"
project-jdk-name="corretto-1.8"
project-jdk-type="JavaSDK" />
</project>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 411 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 411 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 325 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 900 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 KiB

@ -0,0 +1,90 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.9</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
<exclusions>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.18</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
</project>

@ -0,0 +1,18 @@
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// SpringBoot应用启动类
@SpringBootApplication
@MapperScan("com.example.mapper") // 扫描Mapper接口所在的包
public class SpringbootApplication {
// 程序入口
public static void main(String[] args) {
// 启动SpringBoot应用
SpringApplication.run(SpringbootApplication.class, args);
}
}

@ -0,0 +1,9 @@
package com.example.common;
public interface Constants {
String TOKEN = "token";
String USER_DEFAULT_PASSWORD = "123";
}

@ -0,0 +1,90 @@
package com.example.common;
import com.example.common.enums.ResultCodeEnum;
// 统一API响应结果封装类
// 用于标准化所有接口的返回格式
public class Result_ {
// 状态码
private String code;
// 状态描述信息
private String msg;
// 返回的数据内容
private Object data;
// 私有构造函数 - 用于创建带数据的成功结果
// @param data 要返回的数据
private Result_(Object data) {
this.data = data;
}
// 无参构造函数
public Result_() {
}
// 创建成功的空结果(无数据)
// @return 成功结果对象
public static Result_ success() {
Result_ tResult = new Result_();
tResult.setCode(ResultCodeEnum.SUCCESS.code);
tResult.setMsg(ResultCodeEnum.SUCCESS.msg);
return tResult;
}
// 创建成功的带数据结果
// @param data 要返回的数据对象
// @return 成功结果对象
public static Result_ success(Object data) {
Result_ tResult = new Result_(data);
tResult.setCode(ResultCodeEnum.SUCCESS.code);
tResult.setMsg(ResultCodeEnum.SUCCESS.msg);
return tResult;
}
// 创建系统错误结果
// @return 系统错误结果对象
public static Result_ error() {
Result_ tResult = new Result_();
tResult.setCode(ResultCodeEnum.SYSTEM_ERROR.code);
tResult.setMsg(ResultCodeEnum.SYSTEM_ERROR.msg);
return tResult;
}
// 创建自定义错误结果
// @param code 错误码
// @param msg 错误信息
// @return 错误结果对象
public static Result_ error(String code, String msg) {
Result_ tResult = new Result_();
tResult.setCode(code);
tResult.setMsg(msg);
return tResult;
}
// 根据枚举创建错误结果
// @param resultCodeEnum 结果码枚举
// @return 错误结果对象
public static Result_ error(ResultCodeEnum resultCodeEnum) {
Result_ tResult = new Result_();
tResult.setCode(resultCodeEnum.code);
tResult.setMsg(resultCodeEnum.msg);
return tResult;
}
// Getter 和 Setter 方法
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}

@ -0,0 +1,25 @@
package com.example.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
*
*/
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);//// 5 创建并返回CORS过滤器
}
}

@ -0,0 +1,94 @@
package com.example.common.config;
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.exception.CustomException;
import com.example.service.AdminService;
import com.example.service.BusinessService;
import com.example.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* JWT
* JWT
*/
@Component // 声明为Spring组件由Spring容器管理
public class JwtInterceptor implements HandlerInterceptor {
// 日志记录器
private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);
// 注入各种用户服务
@Resource
private AdminService adminService;
@Resource
private BusinessService businessService;
@Resource
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 1. 从HTTP请求头中获取token
String token = request.getHeader(Constants.TOKEN);
if (ObjectUtil.isEmpty(token)) {
// 如果请求头中没有token尝试从请求参数中获取
token = request.getParameter(Constants.TOKEN);
}
// 2. 令牌为空检查
if (ObjectUtil.isEmpty(token)) {
throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
}
Account account = null;
try {
// 3. 解析JWT令牌获取用户信息和角色
// JWT的Audience字段存储了"用户ID-角色"格式的数据
String userRole = JWT.decode(token).getAudience().get(0);
String userId = userRole.split("-")[0]; // 提取用户ID
String role = userRole.split("-")[1]; // 提取用户角色
// 4. 根据角色类型查询对应的用户信息
if (RoleEnum.ADMIN.name().equals(role)) {
account = adminService.selectById(Integer.valueOf(userId));
}
if (RoleEnum.BUSINESS.name().equals(role)) {
account = businessService.selectById(Integer.valueOf(userId));
}
if (RoleEnum.USER.name().equals(role)) {
account = userService.selectById(Integer.valueOf(userId));
}
} catch (Exception e) {
// 令牌解析失败
throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
}
// 5. 用户存在性检查
if (ObjectUtil.isNull(account)) {
throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
}
try {
// 6. 验证令牌签名(使用用户密码作为密钥)这种方式可以确保令牌在用户修改密码后自动失效
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(account.getPassword())).build();
jwtVerifier.verify(token); // 验证token签名
} catch (JWTVerificationException e) {
// 令牌验证失败(签名无效或令牌过期)
throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
}
// 7. 验证通过,放行请求
return true;
}
}

@ -0,0 +1,30 @@
package com.example.common.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* Web MVC
* Web
*/
@Configuration // 标记为Spring配置类Spring启动时会自动加载
public class WebConfig implements WebMvcConfigurer {
@Resource
private JwtInterceptor jwtInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor)// 设置拦截路径:拦截所有请求
.addPathPatterns("/**")// 根路径(通常是首页或欢迎页)
.excludePathPatterns("/")// 用户登录接口
.excludePathPatterns("/login")// 用户注册接口
.excludePathPatterns("/register")// 文件访问路径(允许公开访问静态文件)
.excludePathPatterns("/files/**")// 商品分类相关接口(允许公开查看分类)
.excludePathPatterns("/type/**")// 查询所有公告(允许公开查看公告)
.excludePathPatterns("/notice/selectAll")// 商品相关接口(允许公开浏览商品)
.excludePathPatterns("/goods/**")// 根据商品ID查询评论允许公开查看商品评论
.excludePathPatterns("/comment/selectByGoodsId/**");
}
}

@ -0,0 +1,27 @@
package com.example.common.enums;
public enum ResultCodeEnum {
SUCCESS("200", "成功"),
PARAM_ERROR("400", "参数异常"),
TOKEN_INVALID_ERROR("401", "无效的token"),
TOKEN_CHECK_ERROR("401", "token验证失败请重新登录"),
PARAM_LOST_ERROR("4001", "参数缺失"),
SYSTEM_ERROR("500", "系统异常"),
USER_EXIST_ERROR("5001", "用户名已存在"),
USER_NOT_LOGIN("5002", "用户未登录"),
USER_ACCOUNT_ERROR("5003", "账号或密码错误"),
USER_NOT_EXIST_ERROR("5004", "用户不存在"),
PARAM_PASSWORD_ERROR("5005", "原密码输入错误"),
COLLECT_ALREADY_ERROR("5006","您已收藏过该商品!"),
;
public String code;
public String msg;
ResultCodeEnum(String code, String msg) {
this.code = code;
this.msg = msg;
}
}

@ -0,0 +1,10 @@
package com.example.common.enums;
public enum RoleEnum {
// 管理员
ADMIN,
// 商家
BUSINESS,
// 用户
USER,
}

@ -0,0 +1,14 @@
package com.example.common.enums;
public enum StatusEnum {
CHECKING("审核中"),
CHECK_OK("审核通过"),
CHECK_ON("审核不通过")
;
public String status;
StatusEnum(String status) {
this.status = status;
}
}

@ -0,0 +1,70 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Address;
import com.example.service.AddressService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 地址控制器
@RestController
@RequestMapping("/address")
public class AddressController {
@Resource
private AddressService addressService;
// 新增地址
@PostMapping("/add")
public Result_ add(@RequestBody Address address) {
addressService.add(address);
return Result_.success();
}
// 根据ID删除地址
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
addressService.deleteById(id);
return Result_.success();
}
// 批量删除地址
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
addressService.deleteBatch(ids);
return Result_.success();
}
// 根据ID更新地址信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Address address) {
addressService.updateById(address);
return Result_.success();
}
// 根据ID查询地址
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
Address address = addressService.selectById(id);
return Result_.success(address);
}
// 查询所有地址(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Address address ) {
List<Address> list = addressService.selectAll(address);
return Result_.success(list);
}
// 分页查询地址
@GetMapping("/selectPage")
public Result_ selectPage(Address address,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Address> page = addressService.selectPage(address, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,70 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Admin;
import com.example.service.AdminService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 管理员前端操作接口
@RestController
@RequestMapping("/admin")
public class AdminController {
@Resource
private AdminService adminService;
// 新增管理员
@PostMapping("/add")
public Result_ add(@RequestBody Admin admin) {
adminService.add(admin);
return Result_.success();
}
// 根据ID删除管理员
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
adminService.deleteById(id);
return Result_.success();
}
// 批量删除管理员
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
adminService.deleteBatch(ids);
return Result_.success();
}
// 修改管理员信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Admin admin) {
adminService.updateById(admin);
return Result_.success();
}
// 根据ID查询管理员
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
Admin admin = adminService.selectById(id);
return Result_.success(admin);
}
// 查询所有管理员(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Admin admin ) {
List<Admin> list = adminService.selectAll(admin);
return Result_.success(list);
}
// 分页查询管理员
@GetMapping("/selectPage")
public Result_ selectPage(Admin admin,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Admin> page = adminService.selectPage(admin, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,71 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Business;
import com.example.service.BusinessService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 功能:商家信息处理接口
@RestController
@RequestMapping("/business")
public class BusinessController {
@Resource
private BusinessService businessService;
// 新增商家
@PostMapping("/add")
public Result_ add(@RequestBody Business business) {
businessService.add(business);
return Result_.success();
}
// 根据ID删除商家
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
businessService.deleteById(id);
return Result_.success();
}
// 批量删除商家
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
businessService.deleteBatch(ids);
return Result_.success();
}
// 修改商家信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Business business) {
businessService.updateById(business);
return Result_.success();
}
// 根据ID查询商家
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
Business business = businessService.selectById(id);
return Result_.success(business);
}
// 查询所有商家(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Business business ) {
List<Business> list = businessService.selectAll(business);
return Result_.success(list);
}
// 分页查询商家
@GetMapping("/selectPage")
public Result_ selectPage(Business business,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Business> page = businessService.selectPage(business, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,72 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Cart;
import com.example.service.CartService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 功能:购物车前端操作接口
@RestController
@RequestMapping("/cart")
public class CartController {
@Resource
private CartService cartService;
// 新增购物车商品
@PostMapping("/add")
public Result_ add(@RequestBody Cart cart) {
cartService.add(cart);
return Result_.success();
}
// 根据ID删除购物车商品
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
cartService.deleteById(id);
return Result_.success();
}
// 批量删除购物车商品
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
cartService.deleteBatch(ids);
return Result_.success();
}
// 修改购物车商品信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Cart cart) {
cartService.updateById(cart);
return Result_.success();
}
// 根据ID查询购物车商品
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
Cart cart = cartService.selectById(id);
return Result_.success(cart);
}
// 查询所有购物车商品(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Cart cart ) {
List<Cart> list = cartService.selectAll(cart);
return Result_.success(list);
}
// 分页查询购物车商品
@GetMapping("/selectPage")
public Result_ selectPage(Cart cart,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Cart> page = cartService.selectPage(cart, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,72 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Collect;
import com.example.service.CollectService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 功能:收藏接口
@RestController
@RequestMapping("/collect")
public class CollectController {
// 依赖注入收藏服务
@Resource
private CollectService collectService;
// 新增收藏
@PostMapping("/add")
public Result_ add(@RequestBody Collect collect) {
collectService.add(collect);
return Result_.success();
}
// 根据ID删除收藏
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
collectService.deleteById(id);
return Result_.success();
}
// 批量删除收藏
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
collectService.deleteBatch(ids);
return Result_.success();
}
// 修改收藏信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Collect collect) {
collectService.updateById(collect);
return Result_.success();
}
// 根据ID查询收藏
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
Collect collect = collectService.selectById(id);
return Result_.success(collect);
}
// 查询所有收藏(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Collect collect ) {
List<Collect> list = collectService.selectAll(collect);
return Result_.success(list);
}
// 分页查询收藏
@GetMapping("/selectPage")
public Result_ selectPage(Collect collect,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Collect> page = collectService.selectPage(collect, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,79 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Comment;
import com.example.service.CommentService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 功能:前台评论接口
@RestController
@RequestMapping("/comment")
public class CommentController {
// 依赖注入评论服务
@Resource
private CommentService commentService;
// 新增评论
@PostMapping("/add")
public Result_ add(@RequestBody Comment comment) {
commentService.add(comment);
return Result_.success();
}
// 根据ID删除评论
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
commentService.deleteById(id);
return Result_.success();
}
// 批量删除评论
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
commentService.deleteBatch(ids);
return Result_.success();
}
// 修改评论信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Comment comment) {
commentService.updateById(comment);
return Result_.success();
}
// 根据ID查询评论
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
Comment comment = commentService.selectById(id);
return Result_.success(comment);
}
// 根据商品ID查询评论列表
@GetMapping("/selectByGoodsId")
public Result_ selectByGoodsId(@RequestParam Integer id) {
List<Comment> list = commentService.selectByGoodsId(id);
return Result_.success(list);
}
// 查询所有评论(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Comment comment ) {
List<Comment> list = commentService.selectAll(comment);
return Result_.success(list);
}
// 分页查询评论
@GetMapping("/selectPage")
public Result_ selectPage(Comment comment,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Comment> page = commentService.selectPage(comment, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,110 @@
package com.example.controller;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.example.common.Result_;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
// 文件接口
@RestController
@RequestMapping("/files")
public class FileController {
// 文件上传存储路径项目根目录下的files文件夹
private static final String filePath = System.getProperty("user.dir") + "/files/";
// 服务器端口号默认9090
@Value("${server.port:9090}")
private String port;
// 服务器IP地址默认localhost
@Value("${ip:localhost}")
private String ip;
// 文件上传接口
@PostMapping("/upload")
public Result_ upload(MultipartFile file) {
String flag;
// 使用同步锁确保文件名唯一性
synchronized (FileController.class) {
flag = System.currentTimeMillis() + "";
ThreadUtil.sleep(1L);
}
String fileName = file.getOriginalFilename();
try {
// 如果文件目录不存在,则创建目录
if (!FileUtil.isDirectory(filePath)) {
FileUtil.mkdir(filePath);
}
// 文件存储形式:时间戳-文件名
FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName); // 存储路径示例:***/manager/files/1697438073596-avatar.png
System.out.println(fileName + "--上传成功");
} catch (Exception e) {
System.err.println(fileName + "--文件上传失败");
}
String http = "http://" + ip + ":" + port + "/files/";
// 返回文件访问URLhttp://localhost:9090/files/1697438073596-avatar.png
return Result_.success(http + flag + "-" + fileName);
}
// 文件下载接口
@GetMapping("/{flag}")
public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
OutputStream os;
try {
if (StrUtil.isNotEmpty(flag)) {
// 设置响应头,告诉浏览器以下载方式处理
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, "UTF-8"));
response.setContentType("application/octet-stream");
// 读取文件字节流
byte[] bytes = FileUtil.readBytes(filePath + flag);
os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();
}
} catch (Exception e) {
System.out.println("文件下载失败");
}
}
// 删除文件接口
@DeleteMapping("/{flag}")
public void delFile(@PathVariable String flag) {
FileUtil.del(filePath + flag);
System.out.println("删除文件" + flag + "成功");
}
// wang-editor富文本编辑器文件上传接口
@PostMapping("/wang/upload")
public Map<String, Object> wangEditorUpload(MultipartFile file) {
String flag = System.currentTimeMillis() + "";
String fileName = file.getOriginalFilename();
try {
// 文件存储形式:时间戳-文件名
FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);
System.out.println(fileName + "--上传成功");
Thread.sleep(1L);
} catch (Exception e) {
System.err.println(fileName + "--文件上传失败");
}
String http = "http://" + ip + ":" + port + "/files/";
Map<String, Object> resMap = new HashMap<>();
// wangEditor上传图片成功后需要返回的特定格式参数
resMap.put("errno", 0); // 错误码0表示成功
resMap.put("data", CollUtil.newArrayList(Dict.create().set("url", http + flag + "-" + fileName)));
return resMap;
}
}

@ -0,0 +1,100 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Goods;
import com.example.service.GoodsService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 功能:商品信息处理
@RestController
@RequestMapping("/goods")
public class GoodsController {
// 依赖注入商品服务
@Resource
private GoodsService goodsService;
// 新增商品
@PostMapping("/add")
public Result_ add(@RequestBody Goods goods) {
goodsService.add(goods);
return Result_.success();
}
// 根据ID删除商品
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
goodsService.deleteById(id);
return Result_.success();
}
// 批量删除商品
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
goodsService.deleteBatch(ids);
return Result_.success();
}
// 修改商品信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Goods goods) {
goodsService.updateById(goods);
return Result_.success();
}
// 根据ID查询商品
@GetMapping("/selectById")
public Result_ selectById(@RequestParam Integer id) {
Goods goods = goodsService.selectById(id);
return Result_.success(goods);
}
// 查询销量前15的商品
@GetMapping("/selectTop15")
public Result_ selectTop15() {
List<Goods> list = goodsService.selectTop15();
return Result_.success(list);
}
// 查询所有商品(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Goods goods ) {
List<Goods> list = goodsService.selectAll(goods);
return Result_.success(list);
}
// 通过分类ID查询商品
@GetMapping("/selectByTypeId")
public Result_ selectByTypeId(@RequestParam Integer id) {
List<Goods> list = goodsService.selectByTypeId(id);
return Result_.success(list);
}
// 前台用户首页搜索接口(根据商品名称搜索)
@GetMapping("/selectByName")
public Result_ selectByName(@RequestParam String name) {
List<Goods> list = goodsService.selectByName(name);
return Result_.success(list);
}
// 根据商家ID查询该商家的所有商品
@GetMapping("/selectByBusinessId")
public Result_ selectByBusinessId(@RequestParam Integer id) {
List<Goods> list = goodsService.selectByBusinessId(id);
return Result_.success(list);
}
// 分页查询商品
@GetMapping("/selectPage")
public Result_ selectPage(Goods goods,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Goods> page = goodsService.selectPage(goods, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,71 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Notice;
import com.example.service.NoticeService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 公告信息表前端操作接口
@RestController
@RequestMapping("/notice")
public class NoticeController {
// 依赖注入公告服务
@Resource
private NoticeService noticeService;
// 新增公告
@PostMapping("/add")
public Result_ add(@RequestBody Notice notice) {
noticeService.add(notice);
return Result_.success();
}
// 根据ID删除公告
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
noticeService.deleteById(id);
return Result_.success();
}
// 批量删除公告
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
noticeService.deleteBatch(ids);
return Result_.success();
}
// 修改公告信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Notice notice) {
noticeService.updateById(notice);
return Result_.success();
}
// 根据ID查询公告
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
Notice notice = noticeService.selectById(id);
return Result_.success(notice);
}
// 查询所有公告(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Notice notice ) {
List<Notice> list = noticeService.selectAll(notice);
return Result_.success(list);
}
// 分页查询公告
@GetMapping("/selectPage")
public Result_ selectPage(Notice notice,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Notice> page = noticeService.selectPage(notice, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,72 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Orders;
import com.example.service.OrdersService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 功能:订单前台接口
@RestController
@RequestMapping("/orders")
public class OrdersController {
// 依赖注入订单服务
@Resource
private OrdersService ordersService;
// 新增订单
@PostMapping("/add")
public Result_ add(@RequestBody Orders orders) {
ordersService.add(orders);
return Result_.success();
}
// 根据ID删除订单
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
ordersService.deleteById(id);
return Result_.success();
}
// 批量删除订单
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
ordersService.deleteBatch(ids);
return Result_.success();
}
// 修改订单信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Orders orders) {
ordersService.updateById(orders);
return Result_.success();
}
// 根据ID查询订单
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
Orders orders = ordersService.selectById(id);
return Result_.success(orders);
}
// 查询所有订单(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Orders orders ) {
List<Orders> list = ordersService.selectAll(orders);
return Result_.success(list);
}
// 分页查询订单
@GetMapping("/selectPage")
public Result_ selectPage(Orders orders,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Orders> page = ordersService.selectPage(orders, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,72 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.Type;
import com.example.service.TypeService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 功能:商品分类管理接口
@RestController
@RequestMapping("/type")
public class TypeController {
// 依赖注入分类服务
@Resource
private TypeService typeService;
// 新增商品分类
@PostMapping("/add")
public Result_ add(@RequestBody Type type) {
typeService.add(type);
return Result_.success();
}
// 根据ID删除商品分类
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
typeService.deleteById(id);
return Result_.success();
}
// 批量删除商品分类
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
typeService.deleteBatch(ids);
return Result_.success();
}
// 修改商品分类信息
@PutMapping("/update")
public Result_ updateById(@RequestBody Type type) {
typeService.updateById(type);
return Result_.success();
}
// 根据ID查询商品分类
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
Type type = typeService.selectById(id);
return Result_.success(type);
}
// 查询所有商品分类(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(Type type) {
List<Type> list = typeService.selectAll(type);
return Result_.success(list);
}
// 分页查询商品分类
@GetMapping("/selectPage")
public Result_ selectPage(Type type,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<Type> page = typeService.selectPage(type, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,72 @@
package com.example.controller;
import com.example.common.Result_;
import com.example.entity.User;
import com.example.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
// 功能:用户管理接口
@RestController
@RequestMapping("/user")
public class UserController {
// 依赖注入用户服务
@Resource
private UserService userService;
// 新增用户
@PostMapping("/add")
public Result_ add(@RequestBody User user) {
userService.add(user);
return Result_.success();
}
// 根据ID删除用户
@DeleteMapping("/delete/{id}")
public Result_ deleteById(@PathVariable Integer id) {
userService.deleteById(id);
return Result_.success();
}
// 批量删除用户
@DeleteMapping("/delete/batch")
public Result_ deleteBatch(@RequestBody List<Integer> ids) {
userService.deleteBatch(ids);
return Result_.success();
}
// 修改用户信息
@PutMapping("/update")
public Result_ updateById(@RequestBody User user) {
userService.updateById(user);
return Result_.success();
}
// 根据ID查询用户
@GetMapping("/selectById/{id}")
public Result_ selectById(@PathVariable Integer id) {
User user = userService.selectById(id);
return Result_.success(user);
}
// 查询所有用户(可带条件)
@GetMapping("/selectAll")
public Result_ selectAll(User user ) {
List<User> list = userService.selectAll(user);
return Result_.success(list);
}
// 分页查询用户
@GetMapping("/selectPage")
public Result_ selectPage(User user,
@RequestParam(defaultValue = "1") Integer pageNum, // 页码默认为1
@RequestParam(defaultValue = "10") Integer pageSize) { // 每页大小默认为10
PageInfo<User> page = userService.selectPage(user, pageNum, pageSize);
return Result_.success(page);
}
}

@ -0,0 +1,99 @@
package com.example.controller;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.common.Result_;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.service.AdminService;
import com.example.service.BusinessService;
import com.example.service.UserService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
*
*/
@RestController
public class WebController {
@Resource
private AdminService adminService;
@Resource
private BusinessService businessService;
@Resource
private UserService userService;
@GetMapping("/")
public Result_ hello() {
return Result_.success("访问成功");
}
/**
*
*/
@PostMapping("/login")
public Result_ login(@RequestBody Account account) {
if (ObjectUtil.isEmpty(account.getUsername()) || ObjectUtil.isEmpty(account.getPassword())
|| ObjectUtil.isEmpty(account.getRole())) {
return Result_.error(ResultCodeEnum.PARAM_LOST_ERROR);
}
if (RoleEnum.ADMIN.name().equals(account.getRole())) {
account = adminService.login(account);
}
if (RoleEnum.BUSINESS.name().equals(account.getRole())) {
account = businessService.login(account);
}
if (RoleEnum.USER.name().equals(account.getRole())) { // 用户登录
account = userService.login(account);
}
return Result_.success(account);
}
/**
*
*/
@PostMapping("/register")
public Result_ register(@RequestBody Account account) {
if (StrUtil.isBlank(account.getUsername()) || StrUtil.isBlank(account.getPassword())
|| ObjectUtil.isEmpty(account.getRole())) {
return Result_.error(ResultCodeEnum.PARAM_LOST_ERROR);
}
if (RoleEnum.ADMIN.name().equals(account.getRole())) {
adminService.register(account);
}
if (RoleEnum.BUSINESS.name().equals(account.getRole())) {
businessService.register(account);
}
if (RoleEnum.USER.name().equals(account.getRole())) { // 用户注册
userService.register(account);
}
return Result_.success();
}
/**
*
*/
@PutMapping("/updatePassword")
public Result_ updatePassword(@RequestBody Account account) {
if (StrUtil.isBlank(account.getUsername()) || StrUtil.isBlank(account.getPassword())
|| ObjectUtil.isEmpty(account.getNewPassword())) {
return Result_.error(ResultCodeEnum.PARAM_LOST_ERROR);
}
if (RoleEnum.ADMIN.name().equals(account.getRole())) { // 管理员修改密码
adminService.updatePassword(account);
}
if (RoleEnum.BUSINESS.name().equals(account.getRole())) { // 商家修改密码
businessService.updatePassword(account);
}
if (RoleEnum.USER.name().equals(account.getRole())) { // 用户修改密码
userService.updatePassword(account);
}
return Result_.success();
}
}

@ -0,0 +1,86 @@
package com.example.entity;
// 角色用户父类
public class Account {
// 用户ID
private Integer id;
// 用户名
private String username;
// 用户姓名
private String name;
// 密码
private String password;
// 角色标识ADMIN、BUSINESS、USER等
private String role;
// 新密码(用于修改密码功能)
private String newPassword;
// 用户头像URL
private String avatar;
// 登录令牌
private String token;
// 获取用户ID
public Integer getId() {
return id;
}
// 设置用户ID
public void setId(Integer id) {
this.id = id;
}
// 获取用户名
public String getUsername() {
return username;
}
// 设置用户名
public void setUsername(String username) {
this.username = username;
}
// 获取用户姓名
public String getName() {
return name;
}
// 设置用户姓名
public void setName(String name) {
this.name = name;
}
// 获取密码
public String getPassword() {
return password;
}
// 设置密码
public void setPassword(String password) {
this.password = password;
}
// 获取角色标识
public String getRole() {
return role;
}
// 设置角色标识
public void setRole(String role) {
this.role = role;
}
// 获取新密码
public String getNewPassword() {
return newPassword;
}
// 设置新密码
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
// 获取用户头像
public String getAvatar() {
return avatar;
}
// 设置用户头像
public void setAvatar(String avatar) {
this.avatar = avatar;
}
// 获取登录令牌
public String getToken() {
return token;
}
// 设置登录令牌
public void setToken(String token) {
this.token = token;
}
}

@ -0,0 +1,60 @@
package com.example.entity;
import java.io.Serializable;
// 功能:地址信息表
public class Address implements Serializable {
// 序列化版本ID
private static final long serialVersionUID = 1L;
// 地址ID
private Integer id;
// 用户ID关联用户表
private Integer userId;
// 收货人姓名
private String username;
// 详细地址
private String useraddress;
// 联系电话
private String phone;
// 获取地址ID
public Integer getId() {
return id;
}
// 设置地址ID
public void setId(Integer id) {
this.id = id;
}
// 获取用户ID
public Integer getUserId() {
return userId;
}
// 设置用户ID
public void setUserId(Integer userId) {
this.userId = userId;
}
// 获取收货人姓名
public String getUsername() {
return username;
}
// 设置收货人姓名
public void setUsername(String username) {
this.username = username;
}
// 获取详细地址
public String getUseraddress() {
return useraddress;
}
// 设置详细地址
public void setUseraddress(String useraddress) {
this.useraddress = useraddress;
}
// 获取联系电话
public String getPhone() {
return phone;
}
// 设置联系电话
public void setPhone(String phone) {
this.phone = phone;
}
}

@ -0,0 +1,102 @@
package com.example.entity;
import java.io.Serializable;
// 管理员实体类
public class Admin extends Account implements Serializable {
// 序列化版本ID
private static final long serialVersionUID = 1L;
// 管理员ID
private Integer id;
// 用户名
private String username;
// 密码
private String password;
// 姓名
private String name;
// 电话
private String phone;
// 邮箱
private String email;
// 头像
private String avatar;
// 角色标识
private String role;
// 获取管理员ID
@Override
public Integer getId() {
return id;
}
// 设置管理员ID
@Override
public void setId(Integer id) {
this.id = id;
}
// 获取用户名
@Override
public String getUsername() {
return username;
}
// 设置用户名
@Override
public void setUsername(String username) {
this.username = username;
}
// 获取密码
@Override
public String getPassword() {
return password;
}
// 设置密码
@Override
public void setPassword(String password) {
this.password = password;
}
// 获取姓名
@Override
public String getName() {
return name;
}
// 设置姓名
@Override
public void setName(String name) {
this.name = name;
}
// 获取电话
public String getPhone() {
return phone;
}
// 设置电话
public void setPhone(String phone) {
this.phone = phone;
}
// 获取邮箱
public String getEmail() {
return email;
}
// 设置邮箱
public void setEmail(String email) {
this.email = email;
}
// 获取头像
@Override
public String getAvatar() {
return avatar;
}
// 设置头像
@Override
public void setAvatar(String avatar) {
this.avatar = avatar;
}
// 获取角色标识
@Override
public String getRole() {
return role;
}
// 设置角色标识
@Override
public void setRole(String role) {
this.role = role;
}
}

@ -0,0 +1,123 @@
package com.example.entity;
import java.io.Serializable;
// 功能:商家实体类
public class Business extends Account implements Serializable {
// 序列化版本ID
private static final long serialVersionUID = 1L;
// 商家ID
private Integer id;
// 用户名
private String username;
// 密码
private String password;
// 商家名称
private String name;
// 联系电话
private String phone;
// 邮箱
private String email;
// 头像
private String avatar;
// 角色标识
private String role;
// 商家描述
private String description;
// 商家状态
private String status;
// 获取商家ID
@Override
public Integer getId() {
return id;
}
// 设置商家ID
@Override
public void setId(Integer id) {
this.id = id;
}
// 获取用户名
@Override
public String getUsername() {
return username;
}
// 设置用户名
@Override
public void setUsername(String username) {
this.username = username;
}
// 获取密码
@Override
public String getPassword() {
return password;
}
// 设置密码
@Override
public void setPassword(String password) {
this.password = password;
}
// 获取商家名称
@Override
public String getName() {
return name;
}
// 设置商家名称
@Override
public void setName(String name) {
this.name = name;
}
// 获取联系电话
public String getPhone() {
return phone;
}
// 设置联系电话
public void setPhone(String phone) {
this.phone = phone;
}
// 获取邮箱
public String getEmail() {
return email;
}
// 设置邮箱
public void setEmail(String email) {
this.email = email;
}
// 获取头像
@Override
public String getAvatar() {
return avatar;
}
// 设置头像
@Override
public void setAvatar(String avatar) {
this.avatar = avatar;
}
// 获取角色标识
@Override
public String getRole() {
return role;
}
// 设置角色标识
@Override
public void setRole(String role) {
this.role = role;
}
// 获取商家描述
public String getDescription() {
return description;
}
// 设置商家描述
public void setDescription(String description) {
this.description = description;
}
// 获取商家状态
public String getStatus() {
return status;
}
// 设置商家状态
public void setStatus(String status) {
this.status = status;
}
}

@ -0,0 +1,113 @@
package com.example.entity;
import java.io.Serializable;
// 功能:购物车信息表
public class Cart implements Serializable {
// 序列化版本ID用于对象序列化
private static final long serialVersionUID = 1L;
// 购物车项唯一标识
private Integer id;
// 关联用户ID标识购物车属于哪个用户
private Integer userId;
// 关联商家ID标识商品所属商家
private Integer businessId;
// 关联商品ID标识购物车中的具体商品
private Integer goodsId;
// 商品数量,用户选择的商品数量
private Integer num;
// 商家名称,用于显示
private String businessName;
// 商品名称,用于显示
private String goodsName;
// 商品图片URL用于前端展示
private String goodsImg;
// 商品单位个、件、kg等
private String goodUnit;
// 商品单价
private Double goodsPrice;
// 获取购物车项ID
public Integer getId() {
return id;
}
// 设置购物车项ID
public void setId(Integer id) {
this.id = id;
}
// 获取用户ID
public Integer getUserId() {
return userId;
}
// 设置用户ID
public void setUserId(Integer userId) {
this.userId = userId;
}
// 获取商家ID
public Integer getBusinessId() {
return businessId;
}
// 设置商家ID
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
// 获取商品ID
public Integer getGoodsId() {
return goodsId;
}
// 设置商品ID
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
// 获取商品数量
public Integer getNum() {
return num;
}
// 设置商品数量
public void setNum(Integer num) {
this.num = num;
}
// 获取商家名称
public String getBusinessName() {
return businessName;
}
// 设置商家名称
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
// 获取商品名称
public String getGoodsName() {
return goodsName;
}
// 设置商品名称
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
// 获取商品图片
public String getGoodsImg() {
return goodsImg;
}
// 设置商品图片
public void setGoodsImg(String goodsImg) {
this.goodsImg = goodsImg;
}
// 获取商品单位
public String getGoodUnit() {
return goodUnit;
}
// 设置商品单位
public void setGoodUnit(String goodUnit) {
this.goodUnit = goodUnit;
}
// 获取商品价格
public Double getGoodsPrice() {
return goodsPrice;
}
// 设置商品价格
public void setGoodsPrice(Double goodsPrice) {
this.goodsPrice = goodsPrice;
}
}

@ -0,0 +1,102 @@
package com.example.entity;
import java.io.Serializable;
// 功能:收藏实体
public class Collect implements Serializable {
// 序列化版本ID用于对象序列化
private static final long serialVersionUID = 1L;
// 收藏记录唯一标识
private Integer id;
// 用户ID标识收藏属于哪个用户
private Integer userId;
// 商家ID标识收藏的商家
private Integer businessId;
// 商品ID标识收藏的具体商品
private Integer goodsId;
// 商家名称,用于前端显示
private String businessName;
// 商品名称,用于前端显示
private String goodsName;
// 商品图片URL用于前端展示
private String goodsImg;
// 商品单位个、件、kg等
private String goodUnit;
// 商品价格
private Double goodsPrice;
// 获取收藏记录ID
public Integer getId() {
return id;
}
// 设置收藏记录ID
public void setId(Integer id) {
this.id = id;
}
// 获取用户ID
public Integer getUserId() {
return userId;
}
// 设置用户ID
public void setUserId(Integer userId) {
this.userId = userId;
}
// 获取商家ID
public Integer getBusinessId() {
return businessId;
}
// 设置商家ID
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
// 获取商品ID
public Integer getGoodsId() {
return goodsId;
}
// 设置商品ID
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
// 获取商家名称
public String getBusinessName() {
return businessName;
}
// 设置商家名称
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
// 获取商品名称
public String getGoodsName() {
return goodsName;
}
// 设置商品名称
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
// 获取商品图片
public String getGoodsImg() {
return goodsImg;
}
// 设置商品图片
public void setGoodsImg(String goodsImg) {
this.goodsImg = goodsImg;
}
// 获取商品单位
public String getGoodUnit() {
return goodUnit;
}
// 设置商品单位
public void setGoodUnit(String goodUnit) {
this.goodUnit = goodUnit;
}
// 获取商品价格
public Double getGoodsPrice() {
return goodsPrice;
}
// 设置商品价格
public void setGoodsPrice(Double goodsPrice) {
this.goodsPrice = goodsPrice;
}
}

@ -0,0 +1,113 @@
package com.example.entity;
import java.io.Serializable;
// 功能:评论信息表
public class Comment implements Serializable {
// 序列化版本ID用于对象序列化
private static final long serialVersionUID = 1L;
// 评论唯一标识
private Integer id;
// 用户ID标识发表评论的用户
private Integer userId;
// 商家ID标识被评论的商家
private Integer businessId;
// 商品ID标识被评论的商品
private Integer goodsId;
// 商家名称,用于前端显示
private String businessName;
// 商品名称,用于前端显示
private String goodsName;
// 用户头像URL用于前端展示评论者头像
private String userAvatar;
// 用户昵称,用于前端显示评论者名称
private String userName;
// 评论时间
private String time;
// 评论内容
private String content;
// 获取评论ID
public Integer getId() {
return id;
}
// 设置评论ID
public void setId(Integer id) {
this.id = id;
}
// 获取用户ID
public Integer getUserId() {
return userId;
}
// 设置用户ID
public void setUserId(Integer userId) {
this.userId = userId;
}
// 获取商家ID
public Integer getBusinessId() {
return businessId;
}
// 设置商家ID
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
// 获取商品ID
public Integer getGoodsId() {
return goodsId;
}
// 设置商品ID
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
// 获取商家名称
public String getBusinessName() {
return businessName;
}
// 设置商家名称
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
// 获取商品名称
public String getGoodsName() {
return goodsName;
}
// 设置商品名称
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
// 获取评论时间
public String getTime() {
return time;
}
// 设置评论时间
public void setTime(String time) {
this.time = time;
}
// 获取评论内容
public String getContent() {
return content;
}
// 设置评论内容
public void setContent(String content) {
this.content = content;
}
// 获取用户头像
public String getUserAvatar() {
return userAvatar;
}
// 设置用户头像
public void setUserAvatar(String userAvatar) {
this.userAvatar = userAvatar;
}
// 获取用户昵称
public String getUserName() {
return userName;
}
// 设置用户昵称
public void setUserName(String userName) {
this.userName = userName;
}
}

@ -0,0 +1,111 @@
package com.example.entity;
import cn.hutool.core.collection.CollectionUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.IntStream;
// 功能:推荐系统核心算法
// 版本1.0
/**
* -
*/
public class CoreMath{
/**
*
* @param key ID
* @param map -
* @param type 0-1-
* @return ID
*/
public static Map<Integer, Double> computeNeighbor(Integer key, Map<Integer, List<RelateDTO>> map, int type) {
Map<Integer, Double> distMap = new TreeMap<>();
List<RelateDTO> userItems = map.get(key);
// 检查目标用户是否有评分数据
if (CollectionUtil.isNotEmpty(userItems)) {
// 遍历所有用户,计算与目标用户的相似度
map.forEach((k, v) -> {
// 排除目标用户自身
if (!k.equals(key)) {
// 计算关系系数(相似度)
double coefficient = relateDist(v, userItems, type);
// 计算关系距离(取绝对值)
double distance = Math.abs(coefficient);
distMap.put(k, distance);
}
});
}
return distMap;
}
/**
*
* @param xList X
* @param yList Y
* @param type 0-1-
* @return
*/
private static double relateDist(List<RelateDTO> xList, List<RelateDTO> yList, int type) {
List<Integer> xs = new ArrayList<>();
List<Integer> ys = new ArrayList<>();
// 根据计算类型匹配共同的评分项
xList.forEach(x -> yList.forEach(y -> {
if (type == 0) {
// 基于物品的协同过滤:找到共同评价过的商品
if (x.getGoodsId().equals(y.getGoodsId())) {
xs.add(x.getIndex());
ys.add(y.getIndex());
}
} else {
// 基于用户的协同过滤:找到共同被评价的用户
if (x.getUseId().equals(y.getUseId())) {
xs.add(x.getIndex());
ys.add(y.getIndex());
}
}
}));
// 计算皮尔森相关系数
return getRelate(xs, ys);
}
/**
* pearson
* 线[-1, 1]
* @param xs X
* @param ys Y
* @return 1-10线
*/
public static double getRelate(List<Integer> xs, List<Integer> ys) {
int n = xs.size();
// 至少需要两个共同评分项才能计算相关性
if (n < 2) {
return 0D;
}
// 计算各个统计量
double Ex = xs.stream().mapToDouble(x -> x).sum(); // X的和
double Ey = ys.stream().mapToDouble(y -> y).sum(); // Y的和
double Ex2 = xs.stream().mapToDouble(x -> Math.pow(x, 2)).sum(); // X平方和
double Ey2 = ys.stream().mapToDouble(y -> Math.pow(y, 2)).sum(); // Y平方和
double Exy = IntStream.range(0, n).mapToDouble(i -> xs.get(i) * ys.get(i)).sum(); // X*Y的和
// 皮尔森相关系数公式计算
double numerator = Exy - Ex * Ey / n; // 分子:协方差
double denominator = Math.sqrt((Ex2 - Math.pow(Ex, 2) / n) * (Ey2 - Math.pow(Ey, 2) / n)); // 分母:标准差乘积
// 防止除零错误
if (denominator == 0) {
return 0D;
}
return numerator / denominator;
}
}

@ -0,0 +1,122 @@
package com.example.entity;
import java.io.Serializable;
// 功能:商品信息表
public class Goods implements Serializable {
// 序列化版本ID用于对象序列化
private static final long serialVersionUID = 1L;
// 商品唯一标识
private Integer id;
// 商品名称
private String name;
// 商品描述
private String description;
// 商品主图URL
private String img;
// 商品价格
private Double price;
// 商品单位个、件、kg等
private String unit;
// 商品库存数量
private Integer count;
// 商品分类ID
private Integer typeId;
// 商家ID
private Integer businessId;
// 商品分类名称(关联查询用)
private String typeName;
// 商家名称(关联查询用)
private String businessName;
// 获取商品ID
public Integer getId() {
return id;
}
// 设置商品ID
public void setId(Integer id) {
this.id = id;
}
// 获取商品名称
public String getName() {
return name;
}
// 设置商品名称
public void setName(String name) {
this.name = name;
}
// 获取商品描述
public String getDescription() {
return description;
}
// 设置商品描述
public void setDescription(String description) {
this.description = description;
}
// 获取商品主图
public String getImg() {
return img;
}
// 设置商品主图
public void setImg(String img) {
this.img = img;
}
// 获取商品价格
public Double getPrice() {
return price;
}
// 设置商品价格
public void setPrice(Double price) {
this.price = price;
}
// 获取商品单位
public String getUnit() {
return unit;
}
// 设置商品单位
public void setUnit(String unit) {
this.unit = unit;
}
// 获取商品库存
public Integer getCount() {
return count;
}
// 设置商品库存
public void setCount(Integer count) {
this.count = count;
}
// 获取分类ID
public Integer getTypeId() {
return typeId;
}
// 设置分类ID
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
// 获取商家ID
public Integer getBusinessId() {
return businessId;
}
// 设置商家ID
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
// 获取分类名称
public String getTypeName() {
return typeName;
}
// 设置分类名称
public void setTypeName(String typeName) {
this.typeName = typeName;
}
// 获取商家名称
public String getBusinessName() {
return businessName;
}
// 设置商家名称
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
}

@ -0,0 +1,61 @@
package com.example.entity;
import java.io.Serializable;
// 公告信息表
public class Notice implements Serializable {
// 序列化版本ID用于对象序列化
private static final long serialVersionUID = 1L;
// 公告唯一标识
private Integer id;
// 公告标题
private String title;
// 公告内容
private String content;
// 公告创建时间
private String time;
// 公告创建人
private String user;
// 获取公告ID
public Integer getId() {
return id;
}
// 设置公告ID
public void setId(Integer id) {
this.id = id;
}
// 获取公告标题
public String getTitle() {
return title;
}
// 设置公告标题
public void setTitle(String title) {
this.title = title;
}
// 获取公告内容
public String getContent() {
return content;
}
// 设置公告内容
public void setContent(String content) {
this.content = content;
}
// 获取创建时间
public String getTime() {
return time;
}
// 设置创建时间
public void setTime(String time) {
this.time = time;
}
// 获取创建人
public String getUser() {
return user;
}
// 设置创建人
public void setUser(String user) {
this.user = user;
}
}

@ -0,0 +1,195 @@
package com.example.entity;
import java.io.Serializable;
import java.util.List;
// 功能:订单信息表
public class Orders implements Serializable {
// 序列化版本ID用于对象序列化
private static final long serialVersionUID = 1L;
// 订单唯一标识
private Integer id;
// 用户ID下单用户
private Integer userId;
// 商家ID商品所属商家
private Integer businessId;
// 商品ID购买的商品
private Integer goodsId;
// 订单编号,业务唯一标识
private String orderId;
// 收货地址ID
private Integer addressId;
// 购买数量
private Integer num;
// 订单总金额
private Double price;
// 订单状态(待付款、待发货、待收货、已完成等)
private String status;
// 购物车数据,用于批量下单
private List<Cart> cartData;
// 商家名称,用于显示
private String businessName;
// 商品名称,用于显示
private String goodsName;
// 商品图片,用于显示
private String goodsImg;
// 商品单位
private String goodsUnit;
// 商品单价
private Double goodsPrice;
// 收货人姓名
private String username;
// 收货地址详情
private String useraddress;
// 收货人电话
private String phone;
// 获取订单ID
public Integer getId() {
return id;
}
// 设置订单ID
public void setId(Integer id) {
this.id = id;
}
// 获取用户ID
public Integer getUserId() {
return userId;
}
// 设置用户ID
public void setUserId(Integer userId) {
this.userId = userId;
}
// 获取商家ID
public Integer getBusinessId() {
return businessId;
}
// 设置商家ID
public void setBusinessId(Integer businessId) {
this.businessId = businessId;
}
// 获取商品ID
public Integer getGoodsId() {
return goodsId;
}
// 设置商品ID
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
// 获取订单编号
public String getOrderId() {
return orderId;
}
// 设置订单编号
public void setOrderId(String orderId) {
this.orderId = orderId;
}
// 获取地址ID
public Integer getAddressId() {
return addressId;
}
// 设置地址ID
public void setAddressId(Integer addressId) {
this.addressId = addressId;
}
// 获取购买数量
public Integer getNum() {
return num;
}
// 设置购买数量
public void setNum(Integer num) {
this.num = num;
}
// 获取订单总金额
public Double getPrice() {
return price;
}
// 设置订单总金额
public void setPrice(Double price) {
this.price = price;
}
// 获取订单状态
public String getStatus() {
return status;
}
// 设置订单状态
public void setStatus(String status) {
this.status = status;
}
// 获取购物车数据
public List<Cart> getCartData() {
return cartData;
}
// 设置购物车数据
public void setCartData(List<Cart> cartData) {
this.cartData = cartData;
}
// 获取商家名称
public String getBusinessName() {
return businessName;
}
// 设置商家名称
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
// 获取商品名称
public String getGoodsName() {
return goodsName;
}
// 设置商品名称
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
// 获取商品图片
public String getGoodsImg() {
return goodsImg;
}
// 设置商品图片
public void setGoodsImg(String goodsImg) {
this.goodsImg = goodsImg;
}
// 获取商品单位
public String getGoodsUnit() {
return goodsUnit;
}
// 设置商品单位
public void setGoodsUnit(String goodsUnit) {
this.goodsUnit = goodsUnit;
}
// 获取商品单价
public Double getGoodsPrice() {
return goodsPrice;
}
// 设置商品单价
public void setGoodsPrice(Double goodsPrice) {
this.goodsPrice = goodsPrice;
}
// 获取收货人姓名
public String getUsername() {
return username;
}
// 设置收货人姓名
public void setUsername(String username) {
this.username = username;
}
// 获取收货地址
public String getUseraddress() {
return useraddress;
}
// 设置收货地址
public void setUseraddress(String useraddress) {
this.useraddress = useraddress;
}
// 获取收货人电话
public String getPhone() {
return phone;
}
// 设置收货人电话
public void setPhone(String phone) {
this.phone = phone;
}
}

@ -0,0 +1,48 @@
package com.example.entity;
// 功能:推荐系统关联关系数据传输对象
public class RelateDTO {
/** 用户id */
private Integer useId;
/** 商品id */
private Integer goodsId;
/** 指数(评分/偏好度) */
private Integer index;
// 构造函数
public RelateDTO(Integer useId, Integer goodsId, Integer index) {
this.useId = useId;
this.goodsId = goodsId;
this.index = index;
}
// 获取用户ID
public Integer getUseId() {
return useId;
}
// 设置用户ID
public void setUseId(Integer useId) {
this.useId = useId;
}
// 获取商品ID
public Integer getGoodsId() {
return goodsId;
}
// 设置商品ID
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
// 获取指数(评分/偏好度)
public Integer getIndex() {
return index;
}
// 设置指数(评分/偏好度)
public void setIndex(Integer index) {
this.index = index;
}
}

@ -0,0 +1,51 @@
package com.example.entity;
import java.io.Serializable;
// 功能:商品分类信息表
public class Type implements Serializable {
// 序列化版本ID用于对象序列化
private static final long serialVersionUID = 1L;
// 分类唯一标识
private Integer id;
// 分类名称
private String name;
// 分类描述
private String description;
// 分类图标URL
private String img;
// 获取分类ID
public Integer getId() {
return id;
}
// 设置分类ID
public void setId(Integer id) {
this.id = id;
}
// 获取分类名称
public String getName() {
return name;
}
// 设置分类名称
public void setName(String name) {
this.name = name;
}
// 获取分类描述
public String getDescription() {
return description;
}
// 设置分类描述
public void setDescription(String description) {
this.description = description;
}
// 获取分类图标
public String getImg() {
return img;
}
// 设置分类图标
public void setImg(String img) {
this.img = img;
}
}

@ -0,0 +1,103 @@
package com.example.entity;
import java.io.Serializable;
// 功能:用户信息表
public class User extends Account implements Serializable {
// 序列化版本ID用于对象序列化
private static final long serialVersionUID = 1L;
// 用户唯一标识
private Integer id;
// 用户名(登录账号)
private String username;
// 密码
private String password;
// 用户昵称
private String name;
// 手机号码
private String phone;
// 邮箱地址
private String email;
// 用户头像URL
private String avatar;
// 角色标识固定为USER
private String role;
// 获取用户ID
@Override
public Integer getId() {
return id;
}
// 设置用户ID
@Override
public void setId(Integer id) {
this.id = id;
}
// 获取用户名
@Override
public String getUsername() {
return username;
}
// 设置用户名
@Override
public void setUsername(String username) {
this.username = username;
}
// 获取密码
@Override
public String getPassword() {
return password;
}
// 设置密码
@Override
public void setPassword(String password) {
this.password = password;
}
// 获取用户昵称
@Override
public String getName() {
return name;
}
// 设置用户昵称
@Override
public void setName(String name) {
this.name = name;
}
// 获取手机号码
public String getPhone() {
return phone;
}
// 设置手机号码
public void setPhone(String phone) {
this.phone = phone;
}
// 获取邮箱地址
public String getEmail() {
return email;
}
// 设置邮箱地址
public void setEmail(String email) {
this.email = email;
}
// 获取用户头像
@Override
public String getAvatar() {
return avatar;
}
// 设置用户头像
@Override
public void setAvatar(String avatar) {
this.avatar = avatar;
}
// 获取角色标识
@Override
public String getRole() {
return role;
}
// 设置角色标识
@Override
public void setRole(String role) {
this.role = role;
}
}

@ -0,0 +1,61 @@
package com.example.entity;
import cn.hutool.core.collection.CollectionUtil;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
// 功能:基于用户的协同过滤推荐算法
public class UserCF {
/**
* : id
*
* @param userId ID
* @param list
* @return {@link List<Integer>} ID
*/
public static List<Integer> recommend(Integer userId, List<RelateDTO> list) {
// 按用户ID分组构建用户-商品评分映射
Map<Integer, List<RelateDTO>> userMap = list.stream().collect(Collectors.groupingBy(RelateDTO::getUseId));
// 获取其他用户与当前用户的相似度关系值
Map<Integer, Double> userDisMap = CoreMath.computeNeighbor(userId, userMap, 0);
// 如果没有找到相似用户,返回空列表
if (CollectionUtil.isEmpty(userDisMap)) {
return Collections.emptyList();
}
// 获取相似度最高的用户(关系最近的用户)
double maxValue = Collections.max(userDisMap.values());
Set<Integer> userIds = userDisMap.entrySet().stream()
.filter(e -> e.getValue() == maxValue)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
// 取任意一个相似度最高的用户
Integer nearestUserId = userIds.stream().findAny().orElse(null);
if (nearestUserId == null) {
return Collections.emptyList();
}
// 获取最近邻用户看过的商品列表
List<Integer> neighborItems = userMap.get(nearestUserId).stream()
.map(RelateDTO::getGoodsId)
.collect(Collectors.toList());
// 获取当前用户看过的商品列表
List<Integer> userItems = userMap.get(userId).stream()
.map(RelateDTO::getGoodsId)
.collect(Collectors.toList());
// 找到最近邻用户看过但当前用户没看过的商品(差集)
neighborItems.removeAll(userItems);
return neighborItems;
}
}

@ -0,0 +1,46 @@
package com.example.exception;
import com.example.common.enums.ResultCodeEnum;
// 自定义异常类 - 用于业务异常处理
public class CustomException extends RuntimeException {
// 异常代码
private String code;
// 异常信息
private String msg;
/**
*
* @param resultCodeEnum
*/
public CustomException(ResultCodeEnum resultCodeEnum) {
this.code = resultCodeEnum.code;
this.msg = resultCodeEnum.msg;
}
/**
*
* @param code
* @param msg
*/
public CustomException(String code, String msg) {
this.code = code;
this.msg = msg;
}
// 获取异常代码
public String getCode() {
return code;
}
// 设置异常代码
public void setCode(String code) {
this.code = code;
}
// 获取异常信息
public String getMsg() {
return msg;
}
// 设置异常信息
public void setMsg(String msg) {
this.msg = msg;
}
}

@ -0,0 +1,46 @@
package com.example.exception;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.example.common.Result_;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
// 全局异常处理器 - 统一处理控制器层异常
@ControllerAdvice(basePackages="com.example.controller")
public class GlobalExceptionHandler {
// 日志记录器
private static final Log log = LogFactory.get();
/**
* @ExceptionHandler,Exception
* @param request HTTP
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody // 返回json串
public Result_ error(HttpServletRequest request, Exception e){
// 记录异常日志,便于排查问题
log.error("异常信息:", e);
// 返回通用的系统错误信息(避免暴露敏感信息给前端)
return Result_.error();
}
/**
*
* @param request HTTP
* @param e
* @return
*/
@ExceptionHandler(CustomException.class)
@ResponseBody // 返回json串
public Result_ customError(HttpServletRequest request, CustomException e){
// 直接返回自定义异常中的错误代码和信息
return Result_.error(e.getCode(), e.getMsg());
}
}

@ -0,0 +1,24 @@
package com.example.mapper;
import com.example.entity.Address;
import java.util.List;
// 地址数据访问接口
public interface AddressMapper {
// 新增地址
int insert(Address address);
// 根据ID删除地址
int deleteById(Integer id);
// 根据ID修改地址
int updateById(Address address);
// 根据ID查询地址
Address selectById(Integer id);
// 查询所有地址(可条件查询)
List<Address> selectAll(Address address);
}

@ -0,0 +1,28 @@
package com.example.mapper;
import com.example.entity.Admin;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// 管理员数据访问接口
public interface AdminMapper {
// 新增管理员
int insert(Admin admin);
// 根据ID删除管理员
int deleteById(Integer id);
// 根据ID修改管理员信息
int updateById(Admin admin);
// 根据ID查询管理员
Admin selectById(Integer id);
// 查询所有管理员(可条件查询)
List<Admin> selectAll(Admin admin);
// 根据用户名查询管理员(用于登录验证)
@Select("select * from admin where username = #{username}")
Admin selectByUsername(String username);
}

@ -0,0 +1,28 @@
package com.example.mapper;
import com.example.entity.Business;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// 商家数据访问接口
public interface BusinessMapper {
// 新增商家
int insert(Business business);
// 根据ID删除商家
int deleteById(Integer id);
// 根据ID修改商家信息
int updateById(Business business);
// 根据ID查询商家
Business selectById(Integer id);
// 查询所有商家(可条件查询)
List<Business> selectAll(Business business);
// 根据用户名查询商家(用于登录验证)
@Select("select * from business where username = #{username}")
Business selectByUsername(String username);
}

@ -0,0 +1,29 @@
package com.example.mapper;
import com.example.entity.Cart;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// 购物车数据访问接口
public interface CartMapper {
// 新增购物车商品
int insert(Cart cart);
// 根据ID删除购物车商品
int deleteById(Integer id);
// 根据ID修改购物车商品
int updateById(Cart cart);
// 根据ID查询购物车商品
Cart selectById(Integer id);
// 查询所有购物车商品(可条件查询)
List<Cart> selectAll(Cart cart);
// 根据用户ID和商品ID查询购物车商品检查是否已存在
@Select("select * from cart where user_id = #{userId} and goods_id = #{goodsId}")
Cart selectByUserIdAndGoodsId(@Param("userId") Integer userId, @Param("goodsId") Integer goodsId);
}

@ -0,0 +1,29 @@
package com.example.mapper;
import com.example.entity.Collect;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// 收藏数据访问接口
public interface CollectMapper {
// 新增收藏
int insert(Collect collect);
// 根据ID删除收藏
int deleteById(Integer id);
// 根据ID修改收藏
int updateById(Collect collect);
// 根据ID查询收藏
Collect selectById(Integer id);
// 查询所有收藏(可条件查询)
List<Collect> selectAll(Collect collect);
// 根据用户ID和商品ID查询收藏检查是否已收藏
@Select("select * from collect where user_id = #{userId} and goods_id = #{goodsId}")
Collect selectByUserIdAndGoodsId(@Param("userId") Integer userId, @Param("goodsId") Integer goodsId);
}

@ -0,0 +1,28 @@
package com.example.mapper;
import com.example.entity.Comment;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// 评论数据访问接口
public interface CommentMapper {
// 新增评论
int insert(Comment comment);
// 根据ID删除评论
int deleteById(Integer id);
// 根据ID修改评论
int updateById(Comment comment);
// 根据ID查询评论
Comment selectById(Integer id);
// 查询所有评论(可条件查询)
List<Comment> selectAll(Comment comment);
// 根据商品ID查询评论关联查询用户信息
@Select("select comment.*, user.avatar as userAvatar, user.name as userName from comment left join user on comment.user_id = user.id where comment.goods_id = #{id}")
List<Comment> selectByGoodsId(Integer id);
}

@ -0,0 +1,40 @@
package com.example.mapper;
import com.example.entity.Goods;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// 商品数据访问接口
public interface GoodsMapper {
// 新增商品
int insert(Goods goods);
// 根据ID删除商品
int deleteById(Integer id);
// 根据ID修改商品
int updateById(Goods goods);
// 根据ID查询商品
Goods selectById(Integer id);
// 查询所有商品(可条件查询)
List<Goods> selectAll(Goods goods);
// 通过分类查询商品
@Select("select * from goods where type_id = #{id}")
List<Goods> selectByTypeId(Integer id);
// 根据商家ID查询该商家的所有商品
@Select("select * from goods where business_id = #{id}")
List<Goods> selectByBusinessId(Integer id);
// 查询销量前15的商品
@Select("select * from goods order by count desc limit 15")
List<Goods> selectTop15();
// 根据商品名称搜索商品
@Select("select * from goods where name like concat('%', #{name}, '%')")
List<Goods> selectByName(String name);
}

@ -0,0 +1,24 @@
package com.example.mapper;
import com.example.entity.Notice;
import java.util.List;
// 公告数据访问接口
public interface NoticeMapper {
// 新增公告
int insert(Notice notice);
// 根据ID删除公告
int deleteById(Integer id);
// 根据ID修改公告
int updateById(Notice notice);
// 根据ID查询公告
Notice selectById(Integer id);
// 查询所有公告(可条件查询)
List<Notice> selectAll(Notice notice);
}

@ -0,0 +1,26 @@
package com.example.mapper;
import com.example.entity.Orders;
import java.util.List;
// 订单数据访问接口
public interface OrdersMapper {
// 新增订单
int insert(Orders orders);
// 根据ID删除订单
int deleteById(Integer id);
// 根据ID修改订单
int updateById(Orders orders);
// 根据ID查询订单
Orders selectById(Integer id);
// 查询所有订单(可条件查询)
List<Orders> selectAll(Orders orders);
// 查询所有已完成订单
List<Orders> selectAllOKOrders();
}

@ -0,0 +1,24 @@
package com.example.mapper;
import com.example.entity.Type;
import java.util.List;
// 商品分类数据访问接口
public interface TypeMapper {
// 新增分类
int insert(Type type);
// 根据ID删除分类
int deleteById(Integer id);
// 根据ID修改分类
int updateById(Type type);
// 根据ID查询分类
Type selectById(Integer id);
// 查询所有分类(可条件查询)
List<Type> selectAll(Type type);
}

@ -0,0 +1,28 @@
package com.example.mapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// 用户数据访问接口
public interface UserMapper {
// 新增用户
int insert(User user);
// 根据ID删除用户
int deleteById(Integer id);
// 根据ID修改用户
int updateById(User user);
// 根据ID查询用户
User selectById(Integer id);
// 查询所有用户(可条件查询)
List<User> selectAll(User user);
// 根据用户名查询用户(用于登录验证)
@Select("select * from user where username = #{username}")
User selectByUsername(String username);
}

@ -0,0 +1,70 @@
package com.example.service;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Address;
import com.example.mapper.AddressMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
// 功能:地址业务处理
@Service
public class AddressService {
@Resource
private AddressMapper addressMapper;
// 新增地址
public void add(Address address) {
addressMapper.insert(address);
}
// 根据ID删除地址
public void deleteById(Integer id) {
addressMapper.deleteById(id);
}
// 批量删除地址
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
addressMapper.deleteById(id);
}
}
// 修改地址
public void updateById(Address address) {
addressMapper.updateById(address);
}
// 根据ID查询地址
public Address selectById(Integer id) {
return addressMapper.selectById(id);
}
// 查询所有地址
public List<Address> selectAll(Address address) {
Account currentUser = TokenUtils.getCurrentUser();
// 普通用户只能查询自己的地址
if (RoleEnum.USER.name().equals(currentUser.getRole())) {
address.setUserId(currentUser.getId());
}
return addressMapper.selectAll(address);
}
// 分页查询地址
public PageInfo<Address> selectPage(Address address, Integer pageNum, Integer pageSize) {
Account currentUser = TokenUtils.getCurrentUser();
// 普通用户只能查询自己的地址
if (RoleEnum.USER.name().equals(currentUser.getRole())) {
address.setUserId(currentUser.getId());
}
PageHelper.startPage(pageNum, pageSize);
List<Address> list = addressMapper.selectAll(address);
return PageInfo.of(list);
}
}

@ -0,0 +1,168 @@
package com.example.service;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.exception.CustomException;
import com.example.mapper.AdminMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
*
*/
@Service
public class AdminService {
// 注入管理员数据访问接口
@Resource
private AdminMapper adminMapper;
/**
*
*/
public void add(Admin admin) {
// 1. 检查用户名是否已存在,防止重复注册
Admin dbAdmin = adminMapper.selectByUsername(admin.getUsername());
if (ObjectUtil.isNotNull(dbAdmin)) {
throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
}
// 2. 设置默认密码:如果用户未输入密码,使用系统默认密码
if (ObjectUtil.isEmpty(admin.getPassword())) {
admin.setPassword(Constants.USER_DEFAULT_PASSWORD);
}
// 3. 设置默认姓名:如果用户未输入姓名,默认使用用户名作为姓名
if (ObjectUtil.isEmpty(admin.getName())) {
admin.setName(admin.getUsername());
}
// 4. 设置角色权限:固定为管理员角色
admin.setRole(RoleEnum.ADMIN.name());
// 5. 保存管理员信息到数据库
adminMapper.insert(admin);
}
/**
* ID
*/
public void deleteById(Integer id) {
adminMapper.deleteById(id);
}
/**
*
*/
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
adminMapper.deleteById(id);
}
}
/**
* ID
*/
public void updateById(Admin admin) {
adminMapper.updateById(admin);
}
/**
* ID
*/
public Admin selectById(Integer id) {
return adminMapper.selectById(id);
}
/**
*
*/
public List<Admin> selectAll(Admin admin) {
return adminMapper.selectAll(admin);
}
/**
*
*/
public PageInfo<Admin> selectPage(Admin admin, Integer pageNum, Integer pageSize) {
// 启动分页查询
PageHelper.startPage(pageNum, pageSize);
// 执行查询
List<Admin> list = adminMapper.selectAll(admin);
// 返回分页结果
return PageInfo.of(list);
}
/**
*
*/
public Account login(Account account) {
// 1. 根据用户名查询管理员信息
Account dbAdmin = adminMapper.selectByUsername(account.getUsername());
// 2. 验证用户是否存在
if (ObjectUtil.isNull(dbAdmin)) {
throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
}
// 3. 验证密码是否正确
if (!account.getPassword().equals(dbAdmin.getPassword())) {
throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
}
// 4. 生成登录token组合用户ID和角色信息使用密码作为密钥加密
String tokenData = dbAdmin.getId() + "-" + RoleEnum.ADMIN.name();
String token = TokenUtils.createToken(tokenData, dbAdmin.getPassword());
// 5. 将token设置到返回对象中
dbAdmin.setToken(token);
return dbAdmin;
}
/**
*
*/
public void register(Account account) {
// 1. 创建管理员对象
Admin admin = new Admin();
// 2. 复制属性将Account对象的属性复制到Admin对象
BeanUtils.copyProperties(account, admin);
// 3. 调用新增方法完成注册
add(admin);
}
/**
*
*/
public void updatePassword(Account account) {
// 1. 根据用户名查询管理员信息
Admin dbAdmin = adminMapper.selectByUsername(account.getUsername());
// 2. 验证用户是否存在
if (ObjectUtil.isNull(dbAdmin)) {
throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
}
// 3. 验证原密码是否正确
if (!account.getPassword().equals(dbAdmin.getPassword())) {
throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
}
// 4. 更新为新密码
dbAdmin.setPassword(account.getNewPassword());
// 5. 保存到数据库
adminMapper.updateById(dbAdmin);
}
}

@ -0,0 +1,127 @@
package com.example.service;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.common.enums.StatusEnum;
import com.example.entity.Account;
import com.example.entity.Business;
import com.example.exception.CustomException;
import com.example.mapper.BusinessMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
// 商家业务处理服务
@Service
public class BusinessService {
@Resource
private BusinessMapper businessMapper;
// 新增商家
public void add(Business business) {
// 检查用户名是否已存在
Business dbBusiness = businessMapper.selectByUsername(business.getUsername());
if (ObjectUtil.isNotNull(dbBusiness)) {
throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
}
// 设置默认密码
if (ObjectUtil.isEmpty(business.getPassword())) {
business.setPassword(Constants.USER_DEFAULT_PASSWORD);
}
// 设置默认商家名称
if (ObjectUtil.isEmpty(business.getName())) {
business.setName(business.getUsername());
}
// 设置默认审核状态
if (ObjectUtil.isEmpty(business.getStatus())) {
business.setStatus(StatusEnum.CHECKING.status);
}
// 设置商家角色
business.setRole(RoleEnum.BUSINESS.name());
// 保存到数据库
businessMapper.insert(business);
}
// 根据ID删除商家
public void deleteById(Integer id) {
businessMapper.deleteById(id);
}
// 批量删除商家
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
businessMapper.deleteById(id);
}
}
// 修改商家信息
public void updateById(Business business) {
businessMapper.updateById(business);
}
// 根据ID查询商家
public Business selectById(Integer id) {
return businessMapper.selectById(id);
}
// 查询所有商家
public List<Business> selectAll(Business business) {
return businessMapper.selectAll(business);
}
// 分页查询商家
public PageInfo<Business> selectPage(Business business, Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Business> list = businessMapper.selectAll(business);
return PageInfo.of(list);
}
// 商家登录
public Account login(Account account) {
// 验证用户名是否存在
Account dbBusiness = businessMapper.selectByUsername(account.getUsername());
if (ObjectUtil.isNull(dbBusiness)) {
throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
}
// 验证密码是否正确
if (!account.getPassword().equals(dbBusiness.getPassword())) {
throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
}
// 生成登录token
String tokenData = dbBusiness.getId() + "-" + RoleEnum.BUSINESS.name();
String token = TokenUtils.createToken(tokenData, dbBusiness.getPassword());
dbBusiness.setToken(token);
return dbBusiness;
}
// 商家注册
public void register(Account account) {
Business business = new Business();
BeanUtils.copyProperties(account, business);
add(business);
}
// 修改密码
public void updatePassword(Account account) {
// 验证用户是否存在
Business dbBusiness = businessMapper.selectByUsername(account.getUsername());
if (ObjectUtil.isNull(dbBusiness)) {
throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
}
// 验证原密码是否正确
if (!account.getPassword().equals(dbBusiness.getPassword())) {
throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
}
// 更新密码
dbBusiness.setPassword(account.getNewPassword());
businessMapper.updateById(dbBusiness);
}
}

@ -0,0 +1,76 @@
package com.example.service;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Cart;
import com.example.mapper.CartMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
// 功能:购物车业务处理
@Service
public class CartService {
@Resource
private CartMapper cartMapper;
// 新增商品到购物车
public void add(Cart cart) {
// 检查用户是否已添加过该商品
Cart dbCart = cartMapper.selectByUserIdAndGoodsId(cart.getUserId(), cart.getGoodsId());
if (ObjectUtil.isNotEmpty(dbCart)) {
// 已存在:数量+1
dbCart.setNum(dbCart.getNum() + 1);
cartMapper.updateById(dbCart);
} else {
// 不存在:新增记录
cartMapper.insert(cart);
}
}
// 根据ID删除购物车商品
public void deleteById(Integer id) {
cartMapper.deleteById(id);
}
// 批量删除购物车商品
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
cartMapper.deleteById(id);
}
}
// 修改购物车商品信息
public void updateById(Cart cart) {
cartMapper.updateById(cart);
}
// 根据ID查询购物车商品
public Cart selectById(Integer id) {
return cartMapper.selectById(id);
}
// 查询所有购物车商品
public List<Cart> selectAll(Cart cart) {
return cartMapper.selectAll(cart);
}
// 分页查询购物车商品
public PageInfo<Cart> selectPage(Cart cart, Integer pageNum, Integer pageSize) {
// 权限控制:普通用户只能查看自己的购物车
Account currentUser = TokenUtils.getCurrentUser();
if (RoleEnum.USER.name().equals(currentUser.getRole())) {
cart.setUserId(currentUser.getId());
}
PageHelper.startPage(pageNum, pageSize);
List<Cart> list = cartMapper.selectAll(cart);
return PageInfo.of(list);
}
}

@ -0,0 +1,75 @@
package com.example.service;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Collect;
import com.example.exception.CustomException;
import com.example.mapper.CollectMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
// 功能:收藏业务处理
@Service
public class CollectService {
@Resource
private CollectMapper collectMapper;
// 新增收藏
public void add(Collect collect) {
// 检查是否已收藏该商品
Collect dbCollect = collectMapper.selectByUserIdAndGoodsId(collect.getUserId(), collect.getGoodsId());
if (ObjectUtil.isNotEmpty(dbCollect)) {
// 已收藏:提示不能重复收藏
throw new CustomException(ResultCodeEnum.COLLECT_ALREADY_ERROR);
}
// 新增收藏记录
collectMapper.insert(collect);
}
// 根据ID删除收藏
public void deleteById(Integer id) {
collectMapper.deleteById(id);
}
// 批量删除收藏
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
collectMapper.deleteById(id);
}
}
// 修改收藏信息
public void updateById(Collect collect) {
collectMapper.updateById(collect);
}
// 根据ID查询收藏
public Collect selectById(Integer id) {
return collectMapper.selectById(id);
}
// 查询所有收藏
public List<Collect> selectAll(Collect collect) {
return collectMapper.selectAll(collect);
}
// 分页查询收藏
public PageInfo<Collect> selectPage(Collect collect, Integer pageNum, Integer pageSize) {
// 权限控制:普通用户只能查看自己的收藏
Account currentUser = TokenUtils.getCurrentUser();
if (RoleEnum.USER.name().equals(currentUser.getRole())) {
collect.setUserId(currentUser.getId());
}
PageHelper.startPage(pageNum, pageSize);
List<Collect> list = collectMapper.selectAll(collect);
return PageInfo.of(list);
}
}

@ -0,0 +1,78 @@
package com.example.service;
import cn.hutool.core.date.DateUtil;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Comment;
import com.example.mapper.CommentMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
// 功能:评论业务处理
@Service
public class CommentService {
@Resource
private CommentMapper commentMapper;
// 新增评论
public void add(Comment comment) {
// 自动设置评论时间为当前时间
comment.setTime(DateUtil.now());
commentMapper.insert(comment);
}
// 根据ID删除评论
public void deleteById(Integer id) {
commentMapper.deleteById(id);
}
// 批量删除评论
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
commentMapper.deleteById(id);
}
}
// 修改评论信息
public void updateById(Comment comment) {
commentMapper.updateById(comment);
}
// 根据ID查询评论
public Comment selectById(Integer id) {
return commentMapper.selectById(id);
}
// 查询所有评论
public List<Comment> selectAll(Comment comment) {
return commentMapper.selectAll(comment);
}
// 分页查询评论
public PageInfo<Comment> selectPage(Comment comment, Integer pageNum, Integer pageSize) {
// 权限控制
Account currentUser = TokenUtils.getCurrentUser();
if (RoleEnum.USER.name().equals(currentUser.getRole())) {
// 普通用户只能查看自己的评论
comment.setUserId(currentUser.getId());
}
if (RoleEnum.BUSINESS.name().equals(currentUser.getRole())) {
// 商家只能查看自己商品的评论
comment.setBusinessId(currentUser.getId());
}
PageHelper.startPage(pageNum, pageSize);
List<Comment> list = commentMapper.selectAll(comment);
return PageInfo.of(list);
}
// 根据商品ID查询评论包含用户信息
public List<Comment> selectByGoodsId(Integer id) {
return commentMapper.selectByGoodsId(id);
}
}

@ -0,0 +1,193 @@
package com.example.service;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.RoleEnum;
import com.example.entity.*;
import com.example.mapper.*;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;
// 功能:商品信息业务处理
@Service
public class GoodsService {
@Resource
private GoodsMapper goodsMapper;
@Resource
private CollectMapper collectMapper;
@Resource
private CartMapper cartMapper;
@Resource
private OrdersMapper ordersMapper;
@Resource
private CommentMapper commentMapper;
@Resource
private UserMapper userMapper;
// 新增商品
public void add(Goods goods) {
// 商家添加商品时自动设置商家ID
Account currentUser = TokenUtils.getCurrentUser();
if (RoleEnum.BUSINESS.name().equals(currentUser.getRole())) {
goods.setBusinessId(currentUser.getId());
}
goodsMapper.insert(goods);
}
// 根据ID删除商品
public void deleteById(Integer id) {
goodsMapper.deleteById(id);
}
// 批量删除商品
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
goodsMapper.deleteById(id);
}
}
// 修改商品信息
public void updateById(Goods goods) {
goodsMapper.updateById(goods);
}
// 根据ID查询商品
public Goods selectById(Integer id) {
return goodsMapper.selectById(id);
}
// 查询销量前15的商品
public List<Goods> selectTop15() {
return goodsMapper.selectTop15();
}
// 通过分类查询商品
public List<Goods> selectByTypeId(Integer id) {
return goodsMapper.selectByTypeId(id);
}
// 根据商家ID查询该商家的所有商品
public List<Goods> selectByBusinessId(Integer id) {
return goodsMapper.selectByBusinessId(id);
}
// 查询所有商品
public List<Goods> selectAll(Goods goods) {
return goodsMapper.selectAll(goods);
}
// 分页查询商品
public PageInfo<Goods> selectPage(Goods goods, Integer pageNum, Integer pageSize) {
// 权限控制:商家只能看到自己店铺的商品
Account currentUser = TokenUtils.getCurrentUser();
if (RoleEnum.BUSINESS.name().equals(currentUser.getRole())) {
goods.setBusinessId(currentUser.getId());
}
PageHelper.startPage(pageNum, pageSize);
List<Goods> list = goodsMapper.selectAll(goods);
return PageInfo.of(list);
}
// 用户首页搜索商品
public List<Goods> selectByName(String name) {
return goodsMapper.selectByName(name);
}
// 商品推荐算法
public List<Goods> recommend() {
Account currentUser = TokenUtils.getCurrentUser();
if (ObjectUtil.isEmpty(currentUser)) {
// 没有用户登录,返回空列表
return new ArrayList<>();
}
// 1. 收集所有用户行为数据
List<Collect> allCollects = collectMapper.selectAll(null); // 收藏数据
List<Cart> allCarts = cartMapper.selectAll(null); // 购物车数据
List<Orders> allOrders = ordersMapper.selectAllOKOrders(); // 已完成订单
List<Comment> allComments = commentMapper.selectAll(null); // 评论数据
List<User> allUsers = userMapper.selectAll(null); // 用户数据
List<Goods> allGoods = goodsMapper.selectAll(null); // 商品数据
// 2. 构建用户-商品关系矩阵
List<RelateDTO> data = new ArrayList<>();
for (Goods goods : allGoods) {
Integer goodsId = goods.getId();
for (User user : allUsers) {
Integer userId = user.getId();
int index = 1; // 基础权重
// 计算用户对商品的偏好程度(权重累加)
// 收藏 +1分
Optional<Collect> collectOptional = allCollects.stream()
.filter(x -> x.getGoodsId().equals(goodsId) && x.getUserId().equals(userId)).findFirst();
if (collectOptional.isPresent()) {
index += 1;
}
// 加入购物车 +2分
Optional<Cart> cartOptional = allCarts.stream()
.filter(x -> x.getGoodsId().equals(goodsId) && x.getUserId().equals(userId)).findFirst();
if (cartOptional.isPresent()) {
index += 2;
}
// 完成订单 +3分
Optional<Orders> ordersOptional = allOrders.stream()
.filter(x -> x.getGoodsId().equals(goodsId) && x.getUserId().equals(userId)).findFirst();
if (ordersOptional.isPresent()) {
index += 3;
}
// 发表评论 +2分
Optional<Comment> commentOptional = allComments.stream()
.filter(x -> x.getGoodsId().equals(goodsId) && x.getUserId().equals(userId)).findFirst();
if (commentOptional.isPresent()) {
index += 2;
}
// 如果用户与商品有交互,记录关系数据
if (index > 1) {
RelateDTO relateDTO = new RelateDTO(userId, goodsId, index);
data.add(relateDTO);
}
}
}
// 3. 使用协同过滤算法进行推荐
List<Integer> goodsIds = UserCF.recommend(currentUser.getId(), data);
// 4. 将商品ID转换为商品对象最多返回10个
List<Goods> recommendResult = goodsIds.stream()
.map(goodsId -> allGoods.stream()
.filter(x -> x.getId().equals(goodsId)).findFirst().orElse(null))
.limit(10).collect(Collectors.toList());
return recommendResult;
}
// 随机获取商品(备用推荐方案)
private List<Goods> getRandomGoods(int num) {
List<Goods> list = new ArrayList<>(num);
List<Goods> goods = goodsMapper.selectAll(null);
for (int i = 0; i < num; i++) {
int index = new Random().nextInt(goods.size());
list.add(goods.get(index));
}
return list;
}
}

@ -0,0 +1,64 @@
package com.example.service;
import cn.hutool.core.date.DateUtil;
import com.example.entity.Account;
import com.example.entity.Notice;
import com.example.mapper.NoticeMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import java.util.List;
// 公告信息表业务处理
@Service
public class NoticeService {
@Resource
private NoticeMapper noticeMapper;
// 新增公告
public void add(Notice notice) {
// 自动设置公告日期为今天
notice.setTime(DateUtil.today());
// 自动设置发布人为当前登录用户
Account currentUser = TokenUtils.getCurrentUser();
notice.setUser(currentUser.getUsername());
noticeMapper.insert(notice);
}
// 根据ID删除公告
public void deleteById(Integer id) {
noticeMapper.deleteById(id);
}
// 批量删除公告
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
noticeMapper.deleteById(id);
}
}
// 修改公告信息
public void updateById(Notice notice) {
noticeMapper.updateById(notice);
}
// 根据ID查询公告
public Notice selectById(Integer id) {
return noticeMapper.selectById(id);
}
// 查询所有公告
public List<Notice> selectAll(Notice notice) {
return noticeMapper.selectAll(notice);
}
// 分页查询公告
public PageInfo<Notice> selectPage(Notice notice, Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Notice> list = noticeMapper.selectAll(notice);
return PageInfo.of(list);
}
}

@ -0,0 +1,95 @@
package com.example.service;
import cn.hutool.core.date.DateUtil;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Cart;
import com.example.entity.Orders;
import com.example.mapper.CartMapper;
import com.example.mapper.OrdersMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
// 功能:订单业务处理
@Service
public class OrdersService {
@Resource
private OrdersMapper ordersMapper;
@Resource
private CartMapper cartMapper;
// 新增订单(从购物车生成订单)
public void add(Orders orders) {
// 生成订单编号:年月日时分秒格式
orders.setOrderId(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
// 遍历购物车中的商品,为每个商品创建订单
for (Cart cart : orders.getCartData()) {
Orders dbOrders = new Orders();
// 复制订单基本信息
BeanUtils.copyProperties(orders, dbOrders);
// 设置商品相关信息
dbOrders.setGoodsId(cart.getGoodsId());
dbOrders.setBusinessId(cart.getBusinessId());
dbOrders.setNum(cart.getNum());
// 计算订单金额:数量 × 单价
dbOrders.setPrice(cart.getNum() * cart.getGoodsPrice());
// 保存订单到数据库
ordersMapper.insert(dbOrders);
// 从购物车中删除已下单的商品
cartMapper.deleteById(cart.getId());
}
}
// 根据ID删除订单
public void deleteById(Integer id) {
ordersMapper.deleteById(id);
}
// 批量删除订单
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
ordersMapper.deleteById(id);
}
}
// 修改订单信息
public void updateById(Orders orders) {
ordersMapper.updateById(orders);
}
// 根据ID查询订单
public Orders selectById(Integer id) {
return ordersMapper.selectById(id);
}
// 查询所有订单
public List<Orders> selectAll(Orders orders) {
return ordersMapper.selectAll(orders);
}
// 分页查询订单
public PageInfo<Orders> selectPage(Orders orders, Integer pageNum, Integer pageSize) {
// 权限控制
Account currentUser = TokenUtils.getCurrentUser();
if (RoleEnum.USER.name().equals(currentUser.getRole())) {
// 普通用户只能查看自己的订单
orders.setUserId(currentUser.getId());
}
if (RoleEnum.BUSINESS.name().equals(currentUser.getRole())) {
// 商家只能查看自己店铺的订单
orders.setBusinessId(currentUser.getId());
}
PageHelper.startPage(pageNum, pageSize);
List<Orders> list = ordersMapper.selectAll(orders);
return PageInfo.of(list);
}
}

@ -0,0 +1,57 @@
package com.example.service;
import com.example.entity.Type;
import com.example.mapper.TypeMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
// 功能:分类信息表处理业务
@Service
public class TypeService {
@Resource
private TypeMapper typeMapper;
// 新增分类
public void add(Type type) {
typeMapper.insert(type);
}
// 根据ID删除分类
public void deleteById(Integer id) {
typeMapper.deleteById(id);
}
// 批量删除分类
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
typeMapper.deleteById(id);
}
}
// 修改分类信息
public void updateById(Type type) {
typeMapper.updateById(type);
}
// 根据ID查询分类
public Type selectById(Integer id) {
return typeMapper.selectById(id);
}
// 查询所有分类
public List<Type> selectAll(Type type) {
return typeMapper.selectAll(type);
}
// 分页查询分类
public PageInfo<Type> selectPage(Type type, Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Type> list = typeMapper.selectAll(type);
return PageInfo.of(list);
}
}

@ -0,0 +1,121 @@
package com.example.service;
import cn.hutool.core.util.ObjectUtil;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
// 功能:普通用户业务处理
@Service
public class UserService {
@Resource
private UserMapper userMapper;
// 新增用户
public void add(User user) {
// 检查用户名是否已存在
User dbUser = userMapper.selectByUsername(user.getUsername());
if (ObjectUtil.isNotNull(dbUser)) {
throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
}
// 设置默认密码
if (ObjectUtil.isEmpty(user.getPassword())) {
user.setPassword(Constants.USER_DEFAULT_PASSWORD);
}
// 设置默认姓名
if (ObjectUtil.isEmpty(user.getName())) {
user.setName(user.getUsername());
}
// 设置用户角色
user.setRole(RoleEnum.USER.name());
userMapper.insert(user);
}
// 根据ID删除用户
public void deleteById(Integer id) {
userMapper.deleteById(id);
}
// 批量删除用户
public void deleteBatch(List<Integer> ids) {
for (Integer id : ids) {
userMapper.deleteById(id);
}
}
// 修改用户信息
public void updateById(User user) {
userMapper.updateById(user);
}
// 根据ID查询用户
public User selectById(Integer id) {
return userMapper.selectById(id);
}
// 查询所有用户
public List<User> selectAll(User user) {
return userMapper.selectAll(user);
}
// 分页查询用户
public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> list = userMapper.selectAll(user);
return PageInfo.of(list);
}
// 用户登录
public Account login(Account account) {
// 验证用户名是否存在
Account dbUser = userMapper.selectByUsername(account.getUsername());
if (ObjectUtil.isNull(dbUser)) {
throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
}
// 验证密码是否正确
if (!account.getPassword().equals(dbUser.getPassword())) {
throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
}
// 生成登录token
String tokenData = dbUser.getId() + "-" + RoleEnum.USER.name();
String token = TokenUtils.createToken(tokenData, dbUser.getPassword());
dbUser.setToken(token);
return dbUser;
}
// 用户注册
public void register(Account account) {
User user = new User();
BeanUtils.copyProperties(account, user);
add(user);
}
// 修改密码
public void updatePassword(Account account) {
// 验证用户是否存在
User dbUser = userMapper.selectByUsername(account.getUsername());
if (ObjectUtil.isNull(dbUser)) {
throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
}
// 验证原密码是否正确
if (!account.getPassword().equals(dbUser.getPassword())) {
throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
}
// 更新密码
dbUser.setPassword(account.getNewPassword());
userMapper.updateById(dbUser);
}
}

@ -0,0 +1,92 @@
package com.example.utils;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.common.Constants;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.service.AdminService;
import com.example.service.BusinessService;
import com.example.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
// Token工具类 - 负责JWT令牌的生成和验证
@Component
public class TokenUtils {
private static final Logger log = LoggerFactory.getLogger(TokenUtils.class);
// 静态服务对象 - 用于在静态方法中调用服务
private static AdminService staticAdminService;
private static BusinessService staticBusinessService;
private static UserService staticUserService;
@Resource
AdminService adminService;
@Resource
BusinessService businessService;
@Resource
UserService userService;
// 初始化静态服务对象 - Spring容器启动后自动执行
@PostConstruct
public void setUserService() {
staticAdminService = adminService;
staticBusinessService = businessService;
staticUserService = userService;
}
// 生成JWT Token
public static String createToken(String data, String sign) {
return JWT.create()
.withAudience(data) // 将userId-role保存到token中
.withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
.sign(Algorithm.HMAC256(sign)); // 用密码作为密钥签名
}
// 获取当前登录的用户信息
public static Account getCurrentUser() {
try {
// 获取当前HTTP请求
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 从请求头获取Token
String token = request.getHeader(Constants.TOKEN);
if (ObjectUtil.isNotEmpty(token)) {
// 解析Token获取用户信息
String userRole = JWT.decode(token).getAudience().get(0);
String userId = userRole.split("-")[0]; // 提取用户ID
String role = userRole.split("-")[1]; // 提取用户角色
// 根据角色类型返回对应的用户信息
if (RoleEnum.ADMIN.name().equals(role)) {
return staticAdminService.selectById(Integer.valueOf(userId));
}
if (RoleEnum.BUSINESS.name().equals(role)) {
return staticBusinessService.selectById(Integer.valueOf(userId));
}
if (RoleEnum.USER.name().equals(role)) {
return staticUserService.selectById(Integer.valueOf(userId));
}
}
} catch (Exception e) {
// 记录错误日志
log.error("获取当前用户信息出错", e);
}
// 返回空的账号对象(未登录状态)
return new Account();
}
}

@ -0,0 +1,31 @@
server:
port: 9090
# 数据库配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root #你本地的数据库用户名
password: Hjy041213 #你本地的数据库密码
url: jdbc:mysql://localhost:3306/campus?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8&allowPublicKeyRetrieval=true
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
# 配置mybatis实体和xml映射
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.entity
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
# 分页
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
ip: localhost

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 地址表数据映射文件 - 将Java方法映射为SQL语句 -->
<mapper namespace="com.example.mapper.AddressMapper">
<!-- 定义基础字段列表,避免重复编写 -->
<sql id="Base_Column_List">
id,user_id,username,useraddress,phone
</sql>
<!-- 查询所有地址(支持条件查询) -->
<select id="selectAll" resultType="com.example.entity.Address">
select address.*
from address
<where>
<!-- 动态条件:根据传入参数决定是否添加查询条件 -->
<if test="id != null"> and id= #{id}</if>
<if test="userId != null"> and user_id = #{userId}</if>
<if test="username != null"> and username = #{username}</if>
<if test="useraddress != null"> and useraddress = #{useraddress}</if>
<if test="phone != null"> and phone = #{phone}</if>
</where>
</select>
<!-- 根据ID查询单个地址 -->
<select id="selectById" resultType="com.example.entity.Address">
select
<include refid="Base_Column_List" /> <!-- 引用上面定义的字段列表 -->
from address
where id = #{id}
</select>
<!-- 根据ID删除地址 -->
<delete id="deleteById">
delete from address
where id = #{id}
</delete>
<!-- 新增地址(动态插入非空字段) -->
<insert id="insert" parameterType="com.example.entity.Address" useGeneratedKeys="true">
insert into address
<trim prefix="(" suffix=")" suffixOverrides=",">
<!-- 只插入非空的字段 -->
<if test="id != null">id,</if>
<if test="userId != null">user_id,</if>
<if test="username != null">username,</if>
<if test="useraddress != null">useraddress,</if>
<if test="phone != null">phone,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<!-- 对应的值 -->
<if test="id != null">#{id},</if>
<if test="userId != null">#{userId},</if>
<if test="username != null">#{username},</if>
<if test="useraddress != null">#{useraddress},</if>
<if test="phone != null">#{phone},</if>
</trim>
</insert>
<!-- 根据ID修改地址信息动态更新非空字段 -->
<update id="updateById" parameterType="com.example.entity.Address">
update address
<set>
<!-- 只更新非空的字段 -->
<if test="userId != null">
user_id = #{userId},
</if>
<if test="username != null">
username = #{username},
</if>
<if test="useraddress != null">
useraddress = #{useraddress},
</if>
<if test="phone != null">
phone = #{phone},
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,98 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 管理员表数据映射文件 -->
<mapper namespace="com.example.mapper.AdminMapper">
<!-- 定义管理员表基础字段列表 -->
<sql id="Base_Column_List">
id,username,password,name,phone,email,avatar,role
</sql>
<!-- 查询所有管理员(支持条件查询) -->
<select id="selectAll" resultType="com.example.entity.Admin">
select
<include refid="Base_Column_List" />
from admin
<where>
<if test="id != null"> and id= #{id}</if>
<if test="username != null"> and username like concat('%', #{username}, '%')</if> <!-- 用户名模糊查询 -->
<if test="password != null"> and password= #{password}</if>
<if test="name != null"> and name= #{name}</if>
<if test="phone != null"> and phone= #{phone}</if>
<if test="email != null"> and email= #{email}</if>
<if test="avatar != null"> and avatar= #{avatar}</if>
<if test="role != null"> and role= #{role}</if>
</where>
</select>
<!-- 根据ID查询单个管理员 -->
<select id="selectById" resultType="com.example.entity.Admin">
select
<include refid="Base_Column_List" />
from admin
where id = #{id}
</select>
<!-- 根据ID删除管理员 -->
<delete id="deleteById">
delete from admin
where id = #{id}
</delete>
<!-- 新增管理员(动态插入非空字段) -->
<insert id="insert" parameterType="com.example.entity.Admin" useGeneratedKeys="true">
insert into admin
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="username != null">username,</if>
<if test="password != null">password,</if>
<if test="name != null">name,</if>
<if test="phone != null">phone,</if>
<if test="email != null">email,</if>
<if test="avatar != null">avatar,</if>
<if test="role != null">role,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="username != null">#{username},</if>
<if test="password != null">#{password},</if>
<if test="name != null">#{name},</if>
<if test="phone != null">#{phone},</if>
<if test="email != null">#{email},</if>
<if test="avatar != null">#{avatar},</if>
<if test="role != null">#{role},</if>
</trim>
</insert>
<!-- 根据ID修改管理员信息动态更新非空字段 -->
<update id="updateById" parameterType="com.example.entity.Admin">
update admin
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="name != null">
name = #{name},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="email != null">
email = #{email},
</if>
<if test="avatar != null">
avatar = #{avatar},
</if>
<if test="role != null">
role = #{role},
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 商家表数据映射文件 -->
<mapper namespace="com.example.mapper.BusinessMapper">
<!-- 定义商家表基础字段列表 -->
<sql id="Base_Column_List">
id,username,password,name,phone,email,avatar,role,description,status
</sql>
<!-- 查询所有商家(支持条件查询) -->
<select id="selectAll" resultType="com.example.entity.Business">
select
<include refid="Base_Column_List" />
from business
<where>
<if test="id != null"> and id= #{id}</if>
<if test="username != null"> and username like concat('%', #{username}, '%')</if> <!-- 用户名模糊查询 -->
<if test="password != null"> and password= #{password}</if>
<if test="name != null"> and name= #{name}</if>
<if test="phone != null"> and phone= #{phone}</if>
<if test="email != null"> and email= #{email}</if>
<if test="avatar != null"> and avatar= #{avatar}</if>
<if test="role != null"> and role= #{role}</if>
<if test="description != null"> and description= #{description}</if> <!-- 商家描述 -->
<if test="status != null"> and status= #{status}</if> <!-- 商家状态 -->
</where>
</select>
<!-- 根据ID查询单个商家 -->
<select id="selectById" resultType="com.example.entity.Business">
select
<include refid="Base_Column_List" />
from business
where id = #{id}
</select>
<!-- 根据ID删除商家 -->
<delete id="deleteById">
delete from business
where id = #{id}
</delete>
<!-- 新增商家(动态插入非空字段) -->
<insert id="insert" parameterType="com.example.entity.Business" useGeneratedKeys="true">
insert into business
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="username != null">username,</if>
<if test="password != null">password,</if>
<if test="name != null">name,</if>
<if test="phone != null">phone,</if>
<if test="email != null">email,</if>
<if test="avatar != null">avatar,</if>
<if test="role != null">role,</if>
<if test="description != null">description,</if> <!-- 商家描述 -->
<if test="status != null">status,</if> <!-- 商家状态 -->
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="username != null">#{username},</if>
<if test="password != null">#{password},</if>
<if test="name != null">#{name},</if>
<if test="phone != null">#{phone},</if>
<if test="email != null">#{email},</if>
<if test="avatar != null">#{avatar},</if>
<if test="role != null">#{role},</if>
<if test="description != null">#{description},</if>
<if test="status != null">#{status},</if>
</trim>
</insert>
<!-- 根据ID修改商家信息动态更新非空字段 -->
<update id="updateById" parameterType="com.example.entity.Business">
update business
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
<if test="name != null">
name = #{name},
</if>
<if test="phone != null">
phone = #{phone},
</if>
<if test="email != null">
email = #{email},
</if>
<if test="avatar != null">
avatar = #{avatar},
</if>
<if test="role != null">
role = #{role},
</if>
<if test="description != null">
description = #{description}, <!-- 商家描述 -->
</if>
<if test="status != null">
status = #{status}, <!-- 商家状态 -->
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,86 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 购物车表数据映射文件 -->
<mapper namespace="com.example.mapper.CartMapper">
<!-- 定义购物车表基础字段列表 -->
<sql id="Base_Column_List">
id,user_id,business_id,goods_id,num
</sql>
<!-- 查询所有购物车商品(关联查询商家和商品信息) -->
<select id="selectAll" resultType="com.example.entity.Cart">
select cart.*,
business.name as businessName, <!-- 商家名称 -->
goods.img as goodsImg, <!-- 商品图片 -->
goods.name as goodsName, <!-- 商品名称 -->
goods.price as goodsPrice, <!-- 商品价格 -->
goods.unit as goodUnit <!-- 商品单位 -->
from cart
left join business on cart.business_id = business.id <!-- 关联商家表 -->
left join goods on cart.goods_id = goods.id <!-- 关联商品表 -->
<where>
<if test="id != null"> and id= #{id}</if>
<if test="userId != null"> and user_id = #{userId}</if>
<if test="businessId != null"> and business_id = #{businessId}</if>
<if test="goodsId != null"> and goods_id = #{goodsId}</if>
<if test="num != null"> and num = #{num}</if>
</where>
</select>
<!-- 根据ID查询单个购物车商品 -->
<select id="selectById" resultType="com.example.entity.Cart">
select
<include refid="Base_Column_List" />
from cart
where id = #{id}
</select>
<!-- 根据ID删除购物车商品 -->
<delete id="deleteById">
delete from cart
where id = #{id}
</delete>
<!-- 新增购物车商品 -->
<insert id="insert" parameterType="com.example.entity.Cart" useGeneratedKeys="true">
insert into cart
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="userId != null">user_id,</if>
<if test="businessId != null">business_id,</if>
<if test="goodsId != null">goods_id,</if>
<if test="num != null">num,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="userId != null">#{userId},</if>
<if test="businessId != null">#{businessId},</if>
<if test="goodsId != null">#{goodsId},</if>
<if test="num != null">#{num},</if>
</trim>
</insert>
<!-- 根据ID修改购物车商品信息 -->
<update id="updateById" parameterType="com.example.entity.Cart">
update cart
<set>
<if test="userId != null">
user_id = #{userId},
</if>
<if test="businessId != null">
business_id = #{businessId},
</if>
<if test="goodsId != null">
goods_id = #{goodsId},
</if>
<if test="num != null">
num = #{num}, <!-- 商品数量 -->
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 收藏表数据映射文件 -->
<mapper namespace="com.example.mapper.CollectMapper">
<!-- 定义收藏表基础字段列表 -->
<sql id="Base_Column_List">
id,user_id,business_id,goods_id
</sql>
<!-- 查询所有收藏记录(关联查询商家和商品信息) -->
<select id="selectAll" resultType="com.example.entity.Collect">
select collect.*,
business.name as businessName, <!-- 商家名称 -->
goods.img as goodsImg, <!-- 商品图片 -->
goods.name as goodsName, <!-- 商品名称 -->
goods.price as goodsPrice, <!-- 商品价格 -->
goods.unit as goodUnit <!-- 商品单位 -->
from collect
left join business on collect.business_id = business.id <!-- 关联商家表 -->
left join goods on collect.goods_id = goods.id <!-- 关联商品表 -->
<where>
<if test="id != null"> and id= #{id}</if>
<if test="userId != null"> and user_id = #{userId}</if>
<if test="businessId != null"> and business_id = #{businessId}</if>
<if test="goodsId != null"> and goods_id = #{goodsId}</if>
</where>
</select>
<!-- 根据ID查询单个收藏记录 -->
<select id="selectById" resultType="com.example.entity.Collect">
select
<include refid="Base_Column_List" />
from collect
where id = #{id}
</select>
<!-- 根据ID删除收藏记录 -->
<delete id="deleteById">
delete from collect
where id = #{id}
</delete>
<!-- 新增收藏记录 -->
<insert id="insert" parameterType="com.example.entity.Collect" useGeneratedKeys="true">
insert into collect
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="userId != null">user_id,</if>
<if test="businessId != null">business_id,</if>
<if test="goodsId != null">goods_id,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="userId != null">#{userId},</if>
<if test="businessId != null">#{businessId},</if>
<if test="goodsId != null">#{goodsId},</if>
</trim>
</insert>
<!-- 根据ID修改收藏记录 -->
<update id="updateById" parameterType="com.example.entity.Collect">
update collect
<set>
<if test="userId != null">
user_id = #{userId},
</if>
<if test="businessId != null">
business_id = #{businessId},
</if>
<if test="goodsId != null">
goods_id = #{goodsId},
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 评论表数据映射文件 -->
<mapper namespace="com.example.mapper.CommentMapper">
<!-- 定义评论表基础字段列表 -->
<sql id="Base_Column_List">
id,user_id,business_id,goods_id,time,content
</sql>
<!-- 查询所有评论(关联查询商家、商品和用户信息) -->
<select id="selectAll" resultType="com.example.entity.Comment">
select comment.*,
business.name as businessName, <!-- 商家名称 -->
goods.img as goodsImg, <!-- 商品图片 -->
goods.name as goodsName, <!-- 商品名称 -->
goods.price as goodsPrice, <!-- 商品价格 -->
goods.unit as goodUnit, <!-- 商品单位 -->
user.name as userName <!-- 用户昵称 -->
from comment
left join business on comment.business_id = business.id <!-- 关联商家表 -->
left join goods on comment.goods_id = goods.id <!-- 关联商品表 -->
left join user on comment.user_id = user.id <!-- 关联用户表 -->
<where>
<if test="id != null"> and id= #{id}</if>
<if test="userId != null"> and user_id = #{userId}</if>
<if test="businessId != null"> and comment.business_id = #{businessId}</if>
<if test="goodsId != null"> and goods_id = #{goodsId}</if>
<if test="time != null"> and time = #{time}</if>
<if test="content != null"> and content like concat('%', #{content}, '%') </if> <!-- 评论内容模糊搜索 -->
</where>
</select>
<!-- 根据ID查询单个评论 -->
<select id="selectById" resultType="com.example.entity.Comment">
select
<include refid="Base_Column_List" />
from comment
where id = #{id}
</select>
<!-- 根据ID删除评论 -->
<delete id="deleteById">
delete from comment
where id = #{id}
</delete>
<!-- 新增评论 -->
<insert id="insert" parameterType="com.example.entity.Comment" useGeneratedKeys="true">
insert into comment
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="userId != null">user_id,</if>
<if test="businessId != null">business_id,</if>
<if test="goodsId != null">goods_id,</if>
<if test="time != null">time,</if>
<if test="content != null">content,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="userId != null">#{userId},</if>
<if test="businessId != null">#{businessId},</if>
<if test="goodsId != null">#{goodsId},</if>
<if test="time != null">#{time},</if>
<if test="content != null">#{content},</if>
</trim>
</insert>
<!-- 根据ID修改评论信息 -->
<update id="updateById" parameterType="com.example.entity.Comment">
update comment
<set>
<if test="userId != null">
user_id = #{userId},
</if>
<if test="businessId != null">
business_id = #{businessId},
</if>
<if test="goodsId != null">
goods_id = #{goodsId},
</if>
<if test="time != null">
time = #{time},
</if>
<if test="content != null">
content = #{content}, <!-- 评论内容 -->
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,111 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 商品表数据映射文件 -->
<mapper namespace="com.example.mapper.GoodsMapper">
<!-- 定义商品表基础字段列表 -->
<sql id="Base_Column_List">
id,name,description,img,price,unit,count,type_id,business_id
</sql>
<!-- 查询所有商品(关联查询分类和商家信息) -->
<select id="selectAll" resultType="com.example.entity.Goods">
select goods.*,
type.name as typeName, <!-- 分类名称 -->
business.name as businessName <!-- 商家名称 -->
from goods
left join type on goods.type_id = type.id <!-- 关联分类表 -->
left join business on goods.business_id = business.id <!-- 关联商家表 -->
<where>
<if test="id != null"> and id= #{id}</if>
<if test="name != null"> and goods.name like concat('%', #{name}, '%')</if> <!-- 商品名称模糊搜索 -->
<if test="description != null"> and description= #{description}</if>
<if test="img != null"> and img= #{img}</if>
<if test="price != null"> and price= #{price}</if>
<if test="unit != null"> and unit= #{unit}</if>
<if test="count != null"> and count= #{count}</if> <!-- 库存数量 -->
<if test="typeId != null"> and type_id= #{typeId}</if> <!-- 分类ID -->
<if test="businessId != null"> and business_id= #{businessId}</if> <!-- 商家ID -->
</where>
order by id desc <!-- 按ID降序排列新的在前 -->
</select>
<!-- 根据ID查询单个商品关联查询分类和商家信息 -->
<select id="selectById" resultType="com.example.entity.Goods">
select goods.*,
business.name as businessName, <!-- 商家名称 -->
type.name as typeName <!-- 分类名称 -->
from goods
left join business on goods.business_id = business.id <!-- 关联商家表 -->
left join type on goods.type_id = type.id <!-- 关联分类表 -->
where goods.id = #{id}
</select>
<!-- 根据ID删除商品 -->
<delete id="deleteById">
delete from goods
where id = #{id}
</delete>
<!-- 新增商品 -->
<insert id="insert" parameterType="com.example.entity.Goods" useGeneratedKeys="true">
insert into goods
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="name != null">name,</if>
<if test="description != null">description,</if>
<if test="img != null">img,</if>
<if test="price != null">price,</if>
<if test="unit != null">unit,</if>
<if test="count != null">count,</if>
<if test="typeId != null">type_id,</if>
<if test="businessId != null">business_id,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="name != null">#{name},</if>
<if test="description != null">#{description},</if>
<if test="img != null">#{img},</if>
<if test="price != null">#{price},</if>
<if test="unit != null">#{unit},</if>
<if test="count != null">#{count},</if>
<if test="typeId != null">#{typeId},</if>
<if test="businessId != null">#{businessId},</if>
</trim>
</insert>
<!-- 根据ID修改商品信息 -->
<update id="updateById" parameterType="com.example.entity.Goods">
update goods
<set>
<if test="name != null">
name = #{name}, <!-- 商品名称 -->
</if>
<if test="description != null">
description = #{description}, <!-- 商品描述 -->
</if>
<if test="img != null">
img = #{img}, <!-- 商品图片 -->
</if>
<if test="price != null">
price = #{price}, <!-- 商品价格 -->
</if>
<if test="unit != null">
unit = #{unit}, <!-- 商品单位 -->
</if>
<if test="count != null">
count = #{count}, <!-- 库存数量 -->
</if>
<if test="typeId != null">
type_id = #{typeId}, <!-- 分类ID -->
</if>
<if test="businessId != null">
business_id = #{businessId}, <!-- 商家ID -->
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 公告表数据映射文件 -->
<mapper namespace="com.example.mapper.NoticeMapper">
<!-- 定义公告表基础字段列表 -->
<sql id="Base_Column_List">
id,title,content,time,user
</sql>
<!-- 查询所有公告(支持条件查询) -->
<select id="selectAll" resultType="com.example.entity.Notice">
select
<include refid="Base_Column_List" />
from notice
<where>
<if test="id != null"> and id= #{id}</if>
<if test="title != null"> and title like concat('%', #{title}, '%')</if> <!-- 标题模糊搜索 -->
<if test="content != null"> and content= #{content}</if>
<if test="time != null"> and time= #{time}</if>
<if test="user != null"> and user= #{user}</if>
</where>
order by id desc <!-- 按ID降序排列新的公告在前 -->
</select>
<!-- 根据ID查询单个公告 -->
<select id="selectById" resultType="com.example.entity.Notice">
select
<include refid="Base_Column_List" />
from notice
where id = #{id}
</select>
<!-- 根据ID删除公告 -->
<delete id="deleteById">
delete from notice
where id = #{id}
</delete>
<!-- 新增公告 -->
<insert id="insert" parameterType="com.example.entity.Notice" useGeneratedKeys="true">
insert into notice
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="title != null">title,</if>
<if test="content != null">content,</if>
<if test="time != null">time,</if>
<if test="user != null">user,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="title != null">#{title},</if>
<if test="content != null">#{content},</if>
<if test="time != null">#{time},</if>
<if test="user != null">#{user},</if>
</trim>
</insert>
<!-- 根据ID修改公告信息 -->
<update id="updateById" parameterType="com.example.entity.Notice">
update notice
<set>
<if test="title != null">
title = #{title}, <!-- 公告标题 -->
</if>
<if test="content != null">
content = #{content}, <!-- 公告内容 -->
</if>
<if test="time != null">
time = #{time}, <!-- 发布时间 -->
</if>
<if test="user != null">
user = #{user}, <!-- 发布人 -->
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 订单表数据映射文件 -->
<mapper namespace="com.example.mapper.OrdersMapper">
<!-- 定义订单表基础字段列表 -->
<sql id="Base_Column_List">
id,user_id,business_id,goods_id,num,price,address_id,status,order_id
</sql>
<!-- 查询所有订单(关联查询商家、商品和地址信息) -->
<select id="selectAll" resultType="com.example.entity.Orders">
select orders.*,
business.name as businessName, <!-- 商家名称 -->
goods.img as goodsImg, <!-- 商品图片 -->
goods.name as goodsName, <!-- 商品名称 -->
goods.price as goodsPrice, <!-- 商品单价 -->
goods.unit as goodsUnit, <!-- 商品单位 -->
address.username as username, <!-- 收货人姓名 -->
address.useraddress as useraddress, <!-- 收货地址 -->
address.phone as phone <!-- 收货人电话 -->
from orders
left join business on orders.business_id = business.id <!-- 关联商家表 -->
left join goods on orders.goods_id = goods.id <!-- 关联商品表 -->
left join address on orders.address_id = address.id <!-- 关联地址表 -->
<where>
<if test="id != null"> and id= #{id}</if>
<if test="userId != null"> and orders.user_id = #{userId}</if>
<if test="businessId != null"> and orders.business_id = #{businessId}</if>
<if test="goodsId != null"> and goods_id = #{goodsId}</if>
<if test="num != null"> and num = #{num}</if> <!-- 购买数量 -->
<if test="price != null"> and price = #{price}</if> <!-- 订单金额 -->
<if test="addressId != null"> and address_id = #{addressId}</if>
<if test="status != null"> and status = #{status}</if> <!-- 订单状态 -->
<if test="orderId != null"> and order_id = #{orderId}</if> <!-- 订单编号 -->
</where>
</select>
<!-- 根据ID查询单个订单 -->
<select id="selectById" resultType="com.example.entity.Orders">
select
<include refid="Base_Column_List" />
from orders
where id = #{id}
</select>
<!-- 根据ID删除订单 -->
<delete id="deleteById">
delete from orders
where id = #{id}
</delete>
<!-- 新增订单 -->
<insert id="insert" parameterType="com.example.entity.Orders" useGeneratedKeys="true">
insert into orders
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="userId != null">user_id,</if>
<if test="businessId != null">business_id,</if>
<if test="goodsId != null">goods_id,</if>
<if test="num != null">num,</if>
<if test="price != null">price,</if>
<if test="addressId != null">address_id,</if>
<if test="status != null">status,</if>
<if test="orderId != null">order_id,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="userId != null">#{userId},</if>
<if test="businessId != null">#{businessId},</if>
<if test="goodsId != null">#{goodsId},</if>
<if test="num != null">#{num},</if>
<if test="price != null">#{price},</if>
<if test="addressId != null">#{addressId},</if>
<if test="status != null">#{status},</if>
<if test="orderId != null">#{orderId},</if>
</trim>
</insert>
<!-- 根据ID修改订单信息 -->
<update id="updateById" parameterType="com.example.entity.Orders">
update orders
<set>
<if test="userId != null">
user_id = #{userId}, <!-- 用户ID -->
</if>
<if test="businessId != null">
business_id = #{businessId}, <!-- 商家ID -->
</if>
<if test="goodsId != null">
goods_id = #{goodsId}, <!-- 商品ID -->
</if>
<if test="num != null">
num = #{num}, <!-- 购买数量 -->
</if>
<if test="price != null">
price = #{price}, <!-- 订单金额 -->
</if>
<if test="addressId != null">
address_id = #{addressId}, <!-- 地址ID -->
</if>
<if test="status != null">
status = #{status}, <!-- 订单状态 -->
</if>
<if test="orderId != null">
order_id = #{orderId}, <!-- 订单编号 -->
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,75 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 分类表数据映射文件 -->
<mapper namespace="com.example.mapper.TypeMapper">
<!-- 定义分类表基础字段列表 -->
<sql id="Base_Column_List">
id,name,description,img
</sql>
<!-- 查询所有分类(支持条件查询) -->
<select id="selectAll" resultType="com.example.entity.Type">
select
<include refid="Base_Column_List" />
from type
<where>
<if test="id != null"> and id= #{id}</if>
<if test="name != null"> and name like concat('%', #{name}, '%')</if> <!-- 分类名称模糊搜索 -->
<if test="description != null"> and description= #{description}</if>
<if test="img != null"> and img= #{img}</if>
</where>
order by id desc <!-- 按ID降序排列新的分类在前 -->
</select>
<!-- 根据ID查询单个分类 -->
<select id="selectById" resultType="com.example.entity.Type">
select
<include refid="Base_Column_List" />
from type
where id = #{id}
</select>
<!-- 根据ID删除分类 -->
<delete id="deleteById">
delete from type
where id = #{id}
</delete>
<!-- 新增分类 -->
<insert id="insert" parameterType="com.example.entity.Type" useGeneratedKeys="true">
insert into type
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="name != null">name,</if>
<if test="description != null">description,</if>
<if test="img != null">img,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="name != null">#{name},</if>
<if test="description != null">#{description},</if>
<if test="img != null">#{img},</if>
</trim>
</insert>
<!-- 根据ID修改分类信息 -->
<update id="updateById" parameterType="com.example.entity.Type"> <!-- 修正应该是Type而不是Admin -->
update type
<set>
<if test="name != null">
name = #{name}, <!-- 分类名称 -->
</if>
<if test="description != null">
description = #{description}, <!-- 分类描述 -->
</if>
<if test="img != null">
img = #{img}, <!-- 分类图标 -->
</if>
</set>
where id = #{id}
</update>
</mapper>

@ -0,0 +1,98 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 用户表数据映射文件 -->
<mapper namespace="com.example.mapper.UserMapper">
<!-- 定义用户表基础字段列表 -->
<sql id="Base_Column_List">
id,username,password,name,phone,email,avatar,role
</sql>
<!-- 查询所有用户(支持条件查询) -->
<select id="selectAll" resultType="com.example.entity.User">
select
<include refid="Base_Column_List" />
from user
<where>
<if test="id != null"> and id= #{id}</if>
<if test="username != null"> and username like concat('%', #{username}, '%')</if> <!-- 用户名模糊搜索 -->
<if test="password != null"> and password= #{password}</if>
<if test="name != null"> and name= #{name}</if>
<if test="phone != null"> and phone= #{phone}</if>
<if test="email != null"> and email= #{email}</if>
<if test="avatar != null"> and avatar= #{avatar}</if>
<if test="role != null"> and role= #{role}</if>
</where>
</select>
<!-- 根据ID查询单个用户 -->
<select id="selectById" resultType="com.example.entity.User">
select
<include refid="Base_Column_List" />
from user
where id = #{id}
</select>
<!-- 根据ID删除用户 -->
<delete id="deleteById">
delete from user
where id = #{id}
</delete>
<!-- 新增用户 -->
<insert id="insert" parameterType="com.example.entity.User" useGeneratedKeys="true">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="username != null">username,</if>
<if test="password != null">password,</if>
<if test="name != null">name,</if>
<if test="phone != null">phone,</if>
<if test="email != null">email,</if>
<if test="avatar != null">avatar,</if>
<if test="role != null">role,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id},</if>
<if test="username != null">#{username},</if>
<if test="password != null">#{password},</if>
<if test="name != null">#{name},</if>
<if test="phone != null">#{phone},</if>
<if test="email != null">#{email},</if>
<if test="avatar != null">#{avatar},</if>
<if test="role != null">#{role},</if>
</trim>
</insert>
<!-- 根据ID修改用户信息 -->
<update id="updateById" parameterType="com.example.entity.User">
update user
<set>
<if test="username != null">
username = #{username}, <!-- 用户名 -->
</if>
<if test="password != null">
password = #{password}, <!-- 密码 -->
</if>
<if test="name != null">
name = #{name}, <!-- 用户昵称 -->
</if>
<if test="phone != null">
phone = #{phone}, <!-- 手机号码 -->
</if>
<if test="email != null">
email = #{email}, <!-- 邮箱地址 -->
</if>
<if test="avatar != null">
avatar = #{avatar}, <!-- 用户头像 -->
</if>
<if test="role != null">
role = #{role}, <!-- 用户角色 -->
</if>
</set>
where id = #{id}
</update>
</mapper>

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save