开发者文档
1. 配置
1.1 jdk版本:17
1.2 数据库:选用mysql数据库
在application.yml文件中添加以下内容
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
url: jdbc:mysql://localhost:port/schema # todo:用你的数据库地址、端口、架构名替换localhost、port、schema
username: # todo: 添加你的用户名
password: # todo: 添加你的密码
servlet:
multipart:
max-file-size: 200MB
max-request-size: 200MB
1.3 mybatis-plus-join
这个插件可以帮助你方便、快速生成sql语句,如果需要可以在application.yml文件中添加以下内容
mybatis:
table:
# create系统启动后,会将所有的表删除掉,然后根据model中配置的结构重新建表,该操作会破坏原有数据;
# update系统会自动判断哪些表是新建的.哪些字段要修改类型等,哪些字段要删除,哪些字段要新增,该操作不会破坏原有数据;
# add新增表/新增字段/新增索引新增唯一约束的功能,不做做修改和删除(只在版本1.0.9.RELEASE及以上支持);
# none系统不做任何处理;
auto: add
model:
# 扫描用于创建表的对象的包名
pack: com.*.*.model
database:
# 数据库类型目前只支持mysql
type: mysql
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
如果想进行额外配置,需进创建额外config类,具体内容参考官网MyBatis-Plus 或 MyBatis-Plus-Join
package com.se.utils;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.se.forum.mapper")
public class MybatisPlusConfig {
/**
* 添加分页插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加
// 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
return interceptor;
}
}
1.4 token配置
token部分负责与前端交互进行身份确认,同样在application.yml中配置 同时在satoken文件夹中还有其他相关方法
sa-token:
# token 名称(同时也是 cookie 名称)
token-name: satoken
# token 有效期(单位:秒) 默认30天,-1 代表永久有效
timeout: 2592000
# token 最低活跃频率(单位:秒),如果 token 超过此时间没有访问系统就会被冻结,默认-1 代表不限制,永不冻结
active-timeout: -1
# 是否允许同一账号多地同时登录 (为 true 时允许一起登录, 为 false 时新登录挤掉旧登录)
is-concurrent: true
# 在多人登录同一账号时,是否共用一个 token (为 true 时所有登录共用一个 token, 为 false 时每次登录新建一个 token)
is-share: false
# token 风格(默认可取值:uuid、simple-uuid、random-32、random-64、random-128、tik)
token-style: uuid
# 是否输出操作日志
is-log: true
1.5 minio配置
MinIO是在GNU Affero通用公共许可证v3.0下发布的高性能对象存储。 可以用于文件存储,例如图片、pdf、json等。详情见github
下面是application.yml中的配置方式
minio:
endpoint: http://localhost:9000
accessKey: minioadmin
secretKey: minioadmin
bucketName: seproject
userPath: user-img
commentPath: comment-img
commentJsonPath: comment-json
documentImgPath: document-img
documentFilePath: document-file
productPicturePath: product-pic
counselTeacherPath: counsel-teacher
chatFilePath: chat-file
java类使用时,方法如下
@Value("${minio.userPath}")
private String userImgPath;
在resources下的minio文件夹部分中有两个minio启动源文件以及启动脚本,分别对应linux系统以及windows系统 若linux系统下启动不了脚本或其他系统,可前往官网下载其他源文件
存储地址位于minioFile
1.6 邮件配置
如果你希望保留邮件重置密码或者添加其他邮件相关功能,可以进行如下配置,配置过程中用到了qq邮箱的foxmail邮箱功能,需要进行相应调整
mail:
host: smtp.qq.com # 邮件服务器地址
port: 587 # 端口号
username: # todo 填写邮箱地址
password: # todo 填写登录密码
default-encoding: UTF-8 # 默认编码格式
properties:
mail:
debug: false # 启动debug调试
smtp:
socketFactoryClass: javax.net.ssl.SSLSocketFactory
socketFactory:
class: javax.net.ssl.SSLSocketFactory # SSL连接配置
2. 代码
2.1 一键代码生成
可以依据数据库中的表格创建相对应的软件包,结构如下
table
├── controller
│ └── TableController.java
├── entity
│ └── Table.java
├── mapper
│ └── TableMapper.java
└── service
├── TableService.java
└── impl
└── TableServiceImpl.java
package com.se.utils;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
public class codeGenerator {
public static void main(String[] args) {
// 1、创建代码生成器
AutoGenerator mpg = new AutoGenerator();
// 2、全局配置
// 全局配置
GlobalConfig gc = new GlobalConfig();
// TODO:设置生成文件的输出目录
gc.setOutputDir("backend文件夹所在位置(直接路径)" + "/src/main/java");
// 去掉Service接口的首字母I
gc.setServiceName("%sService");
// TODO:设置作者
gc.setAuthor("你的名字");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 3、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
// TODO:设置数据库连接信息
dsc.setUrl("jdbc:mysql://host:port/schema");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("username");
dsc.setPassword("password");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
// 4、包配置
PackageConfig pc = new PackageConfig();
// TODO:设置包名,
pc.setParent("com.*");
// 模块名
// pc.setModuleName("sys");
pc.setController("controller");
pc.setService("service");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 5、策略配置
StrategyConfig strategy = new StrategyConfig();
// TODO:需要生成的表名
strategy.setInclude("tanle");
// 数据库表映射到实体的命名策略
strategy.setNaming(NamingStrategy.underline_to_camel);
// 数据库表字段映射到实体的命名策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// lombok 模型 @Accessors(chain = true) setter链式操作
strategy.setEntityLombokModel(true);
// restful api风格控制器
strategy.setRestControllerStyle(true);
// url中驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
// 与MPJ(mybatis-plus-join)对应的mapper
strategy.setSuperMapperClass("com.github.yulichang.base.MPJBaseMapper");
// 设置策略
mpg.setStrategy(strategy);
// 6、执行
mpg.execute();
}
}
生成软件包之后,需要在SoftwareApplication.java文件中添加 @SpringBootApplication(scanBasePackages = {"", ".table", ".table", ...}) @MapperScan(basePackages = {".mapper", "*.mapper", ...})
2.2 所需方法补全
2.2.1 entity
entity中会自动包含一个Table.java
package com.se.table.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author 作者
* @since 自动生成时间
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class Table implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@TableId(value = "主键名字", type = IdType.AUTO)
private Long tableId;
private String column1;
private Boolean column2;
private LocalDateTime column3;
// ......
}
如有需要可以创建dto,将不同table进行join组合操作,形成一个虚拟表,可能会在从数据库获取数据时使用
2.2.2 mapper
TableMapper不需要进行额外操作
package com.se.table.mapper;
import com.github.yulichang.base.MPJBaseMapper;
import com.se.table.entity.table;
/**
* <p>
* Mapper 接口
* </p>
*
* @author 作者
* @since 自动生成时间
*/
public interface TableMapper extends MPJBaseMapper<Table> {
}
2.2.3 service
TableService和TableServiceImpl是接口以及实现类
在TableService中列举出有需要的方法
package com.se.table.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.se.table.entity.Table;
import com.se.table.entity.TableDTO;
import com.se.table.entity.UnreadTableCountDTO;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务类
* </p>
*
* @author 作者
* @since 自动生成时间
*/
public interface TableService extends IService<Table> {
Table findById(Long tableId);
Integer deleteTable(Long tableId);
List<Table> listAll();
// ......
}
2.2.4 impl
在TableServiceImpl中实现方法,与数据库交互获得符合要求的数据,注解@Autowired可以保持一致性
package com.se.table.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.se.table.entity.Table;
import com.se.table.entity.TableDTO;
import com.se.table.entity.UnreadTableCountDTO;
import com.se.table.mapper.TableMapper;
import com.se.table.service.TableService;
import com.se.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务实现类
* </p>
*
* @author wqy
* @since 2024-05-06
*/
@Service
public class TableServiceImpl extends ServiceImpl<TableMapper, Table> implements TableService {
@Autowired
TableMapper mapper;
@Override
public Table findById(Long tableId) {
MPJLambdaWrapper<Table> queryWrapper = new MPJLambdaWrapper<Table>()
.selectAll(Table.class)
.eq(Table::getTableId, tableId);
return mapper.selectOne(queryWrapper);
}
@Override
public Integer deleteTable(Long tableId) {
return mapper.deleteJoin(JoinWrappers.delete(Table.class)
.delete(Table.class)
.eq(Table::getTableId, tableId));
}
@Override
public List<Table> listAll() {
MPJLambdaWrapper<Table> queryWrapper = new MPJLambdaWrapper<Table>()
.selectAll(Table.class);
return mapper.selectList(queryWrapper);
}
// ......
}
其中MPJLambdaWrapper<>可替换为MPJQueryWrapper
selectList必须要用dto建立数据库中的数据以及取出数据名称之间的联系,得到一个List数组 其中可以使用selectCollection、selectAssociation等方法进行嵌套
selectJoinPage也需要dto建立联系,但可以做到分页操作,根据页条目大小以及当前页面数得到仅所需页面数据
selectJoinMap不需要使用dto,直接将数据插入到map<String, Object>当中,但是不能进行嵌套操作
2.2.5 controller
controller负责与前端进行交互,从前端获得请求,给前端发送数据
@RequestMapping("/table")、@GetMapping("/deleteTable")部分依次分级填写网络地址
@ApiOperation(value = "添加教师信息", tags = "课程类")是swaggerUI相关注解,tags代表类别、value代表名字、note代表注释
@RequestParam注解表明此参数是必须的
package com.se.table.controller;
import com.se.table.entity.Table;
import com.se.table.service.TableService;
import com.se.utils.AjaxJson;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author 作者
* @since 自动生成时间
*/
@RestController
@RequestMapping("/table")
public class TableController {
@Autowired
TableService service;
@ApiOperation(value = "添加教师信息", tags = "课程类")
@GetMapping("/addTable")
public AjaxJson addTable(Table table) {
if (table.getTableName() == null || table.getTableName().isEmpty())
return AjaxJson.getError("教师名不能为空");
if (service.saveOrUpdate(table))
return AjaxJson.getSuccessData(table.getTableId());
return AjaxJson.get(504, "出现未知错误!");
}
@ApiOperation(value = "清除教师信息", tags = "课程类")
@GetMapping("/deleteTable")
public AjaxJson deleteTable(@RequestParam String tableName) {
Table table = service.findByName(tableName);
if (table == null)
return AjaxJson.getError("该教师不存在");
return AjaxJson.getSuccessData(service.deleteTable(table));
}
@ApiOperation(value = "查看所有教师信息", tags = "课程类")
@GetMapping("/listAll")
public AjaxJson listAll() {
return AjaxJson.getSuccessData(service.listAll());
}
// ......
}
AjaxJson是utils中为返回值进行包装的class,将数据转为json格式
2.3 其他内容配置
支付宝,邮件等功能均在utils文件中
另外,global文件中存了一些全局变量,就绪有需要可以通过该文件夹中的方法添加在global表中
3. 运行
3.1 运行SoftwareApplication.java文件,开启后端
3.2 运行minio脚本,启动minio文件存储仓库
3.3(可选) 访问host:springboot_port/swagger-ui.html访问swaggerUI网页进行api查询检测
3.4(可选) 访问host:minio_port访问minio网页进行云端存储仓库查询检测
3.5(可选) 改写pmd.xml,运行下述命令,获得PMD检测报告
mvn clean -DskipTests install