一、springboot启动类依赖:

org.springframework.boot

spring-boot-starter

二、springboot测试类依赖:

org.springframework.boot

spring-boot-starter-test

三、mybatis-plus依赖:

com.baomidou

mybatis-plus-boot-starter

3.4.0

四、lombok依赖(用来简化对类的操作包括:set、get以及构造函数等,只需要 一个注解)

org.projectlombok

lombok

导入lombok依赖后还需要进行一步操作,下载lombok插件,方法:点击File—>Setting—>Plugins

然后再搜索框搜索Lombok,安装插件即可。

五、mysql连接所需要的依赖:

mysql

mysql-connector-java

导入了mysql依赖后需要连接数据库,在application.yaml配置文件中配置连入数据库的参数,url:跟自己数据库的地址,我的数据库名字为mybats-plus,driver后面不变,username和password填上自己数据库的名字和密码即可连接。

spring:

datasource:

url: jdbc:mysql://localhost:3306/mybatis-plus?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8

driver-class-name: com.mysql.cj.jdbc.Driver

username: root

password: huyannan*****

六、配置日志,查看sql输出日志(在application.yaml配置文件中配置)

mybatis-plus:

configuration:

log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

七、 项目启动报错“javax.xml.bind.DatatypeConverter(jdk9以上版本)

这是由于java版本过高,之前java 8及以前的版本是默认包含jaxb-api包的,但是升级后的版本就需要手动来导入这个包了。所以找到pom.xml文件,然后在里边添加如下依赖

javax.xml.bind

jaxb-api

2.3.0

com.sun.xml.bind

jaxb-impl

2.3.0

com.sun.xml.bind

jaxb-core

2.3.0

javax.activation

activation

1.1.1

八、redis依赖:

org.springframework.boot

spring-boot-starter-data-redis

九、fastjson依赖 :可以将 Java 对象转换为 JSON 格式,当然它也可以将 JSON 字符串转换为 Java 对象

com.alibaba

fastjson

1.2.33

十、jwt依赖

io.jsonwebtoken

jjwt

0.9.1

十一、打包跳过测试

org.apache.maven.plugins

maven-surefire-plugin

2.5

true

细节配置

设置主键自动增长:

        1、需要在创建数据表的时候设置主键自增。

        2、实体字段中配置@TableId(value = "id",type = IdType.AUTO)

@Data

@AllArgsConstructor

@NoArgsConstructor

public class User {

@TableId(value = "id",type = IdType.AUTO)

private Long Id;

private String Name;

private Integer Age;

private String Email;

}

添加自动填充功能: 

1、在实体类里面对需要自动填充的属性字段添加注解。

@Data

@AllArgsConstructor

@NoArgsConstructor

public class User {

//@TableId(value = "id",type = IdType.AUTO)

//可以不用设置字段自动增长,mybatis-plus自带雪花算法

private Long id;

private String name;

private Integer age;

private String email;

@TableField(fill = FieldFill.INSERT)

private Date createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)

private Date updateTime;

}

2、自定义实现类 MyMetaObjectHandler,实现MetaObjectHandler接口,实现接口里面的方法

package com.hu.mybatisplus01.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

@Component

public class MyMetaObjectHandler implements MetaObjectHandler {

/**

* 使用mybatis-plus进行添加操作时,会自动执行这个方法

* @param metaObject

*/

@Override

public void insertFill(MetaObject metaObject) {

this.setFieldValByName("createTime",new Date(),metaObject);

this.setFieldValByName("updateTime", new Date(), metaObject);

}

/**

* 使用mybatis-plus进行更新操作时,会自动执行这个方法

* @param metaObject

*/

@Override

public void updateFill(MetaObject metaObject) {

this.setFieldValByName("updateTime",new Date(),metaObject);

}

}

添加乐观锁功能(防止丢失更新,一般只有在并发操作下发生): 

1、在数据库中添加version字段。

2、在实体类中添加version字段并在该字段上添加@Version注解。

public class User {

//@TableId(value = "id",type = IdType.AUTO)

//可以不用设置字段自动增长,mybatis-plus自带雪花算法

private Long id;

private String name;

private Integer age;

private String email;

@TableField(fill = FieldFill.INSERT)

private Date createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)

private Date updateTime;

@Version

private Integer version;

}

3、配置乐观锁插件,创建一个config配置包,在包下新建一个MybatisPlusConfig配置类。

package com.hu.mybatisplus01.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;

import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;

import org.mybatis.spring.annotation.MapperScan;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

@MapperScan("com.hu.mybatisplus01.mapper")

public class MybatisPlusConfig {

/**

* 乐观锁插件

* @return

*/

@Bean

public MybatisPlusInterceptor mybatisPlusInterceptor() {

MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();

mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

return mybatisPlusInterceptor;

}

}

 4、为了方便version字段值的插入,可以设置自动填充,方法同createTime字段设置类似,在version字段上添加@TableField(fill = FieldFill.INSERT)注解,然后在类 MyMetaObjectHandler中配置填充条件。 

配置分页查询功能:

        在MybatisPlusConfig配置类中添加分页插件,这是新版的,因为从MyBatis-Plus 3.4.0开始,不再使用旧版本的PaginationInterceptor ,而是使用MybatisPlusInterceptor。

public class MybatisPlusConfig {

@Bean

public MybatisPlusInterceptor mybatisPlusInterceptor() {

MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();

//乐观锁插件

mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

//添加分页插件

mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));

return mybatisPlusInterceptor;

}

}

配置逻辑删除插件: 

1、在数据库中添加deleted字段。字段属性为boolean。

2、在实体类中添加deleted字段并加上@TableLogic 和@TableField(fill = FieldFill.INSERT)注解。

3、在application.yaml配置文件中配置逻辑删除默认值。

mybatis-plus:

global-config:

db-config:

logic-delete-value: 1 # 逻辑已删除值(默认为 1)

logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

代码生成器使用:

1、添加pom依赖

org.apache.velocity

velocity-engine-core

2.0

com.baomidou

mybatis-plus-generator

3.4.0

2、mybatis3.5.1以下版本使用

package com.hu.demo;

import com.baomidou.mybatisplus.annotation.DbType;

import com.baomidou.mybatisplus.annotation.IdType;

import com.baomidou.mybatisplus.generator.config.GlobalConfig;

import com.baomidou.mybatisplus.generator.AutoGenerator;

import com.baomidou.mybatisplus.generator.config.*;

import com.baomidou.mybatisplus.generator.config.rules.DateType;

import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import org.junit.Test;

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中

public class CodeGenerator {

@Test

public void run() {

// 代码生成器

AutoGenerator mpg = new AutoGenerator();

// 全局配置

GlobalConfig gc = new GlobalConfig();

String projectPath = System.getProperty("user.dir");

gc.setOutputDir(projectPath + "/src/main/java");

gc.setAuthor("胡雁南");

gc.setOpen(false);

gc.setServiceName("%sService");//去掉Service接口的首字母I

gc.setIdType(IdType.ID_WORKER_STR);

gc.setDateType(DateType.ONLY_DATE);//定义生成的实体类中日期类型

gc.setSwagger2(true);// 实体属性 Swagger2 注解

mpg.setGlobalConfig(gc);

// 数据源配置(改成自己的数据库 )

DataSourceConfig dsc = new DataSourceConfig();

dsc.setUrl("jdbc:mysql://localhost:3306/mybatis-plus?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8");

// dsc.setSchemaName("public");

dsc.setDriverName("com.mysql.cj.jdbc.Driver");

dsc.setUsername("root");

dsc.setPassword("huyannan");

dsc.setDbType(DbType.MYSQL);

mpg.setDataSource(dsc);

// 包配置

PackageConfig pc = new PackageConfig();

pc.setParent("com.hu");//com.hu

pc.setModuleName("eduservice");//模块名;;com.hu.eduservice

//包com.hu.eduservice.controller

pc.setController("controller");

pc.setEntity("entity");

pc.setService("service");

pc.setMapper("mapper");

mpg.setPackageInfo(pc);

// 策略配置

StrategyConfig strategy = new StrategyConfig();

strategy.setInclude("edu_teacher");//具体表

strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略

strategy.setTablePrefix(pc.getModuleName() + "_");//生成实体时去掉表前缀

strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略

strategy.setEntityLombokModel(true);//Lombok模型

strategy.setRestControllerStyle(true);//restful api风格控制器

strategy.setControllerMappingHyphenStyle(true);//url中驼峰转连字符

mpg.setStrategy(strategy);

mpg.execute();//执行

}

}

配置统一返回的json格式,在application.yaml配置文件中设置:

#返回json的全局时间格式

spring:

jackson:

date-format: yyyy-MM--dd HH:mm:ss

time-zone: GMT+8

建立统一返回结果集:

创建一个utils工具包,在包下建立ResultCode接口和R类,ResultCode接口中配置返回结果码常量,R类用来封装统一返回结果集。

ResultCode代码

package com.hu.utils;

public interface ResultCode {

Integer SUCCESS=20000;//成功

Integer ERROR=20001;//失败

}

R类代码

package com.hu.utils;

import io.swagger.annotations.ApiModelProperty;

import lombok.Data;

import java.util.HashMap;

import java.util.Map;

@Data

public class R {

@ApiModelProperty(value = "是否返回成功")

private Boolean success;

@ApiModelProperty(value = "返回码")

private Integer code;

@ApiModelProperty(value = "返回消息")

private String message;

@ApiModelProperty(value = "返回数据")

private Map data = new HashMap();

private R(){}//构造方法私有化,使外部不能实例化

//成功静态方法

public static R ok(){

R r = new R();

r.setSuccess(true);

r.setCode(ResultCode.SUCCESS);

r.setMessage("成功");

return r;

}

//失败静态方法

public static R error(){

R r = new R();

r.setSuccess(false);

r.setCode(ResultCode.ERROR);

r.setMessage("失败");

return r;

}

//实现链式编程

public R success(Boolean success){

this.setSuccess(success);

return this;

}

public R message(String message){

this.setMessage(message);

return this;

}

public R code(Integer code){

this.setCode(code);

return this;

}

public R data(String key,Object value){

this.data.put(key, value);

return this;

}

public R data(Mapmap){

this.setData(map);

return this;

}

}

统一异常处理:

        在handler处理包下新建一个 GlobalExceptionHandler全局异常统一处理配置类,若有异常前端不会直接提示500错误。

(1)全局异常处理。

package com.hu.handler;

import com.hu.utils.R;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice

public class GlobalExceptionHandler {

@ResponseBody//为了能够返回数据

//指定出现什么异常执行这个方法

@ExceptionHandler(Exception.class)

public R error(Exception e){

e.printStackTrace();

return R.error().message("执行了全局异常处理");

}

}

(2)特定异常

package com.hu.handler;

import com.hu.utils.R;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice

public class GlobalExceptionHandler {

//特定异常

@ResponseBody//为了能够返回数据

@ExceptionHandler(ArithmeticException.class)

public R error(ArithmeticException e){

e.printStackTrace();

return R.error().message("执行了ArithmeticException异常处理");

}

}

(3)自定义异常

第一步先创建自定义的异常类继承RuntimeException。

package com.hu.handler;

import lombok.AllArgsConstructor;

import lombok.Data;

import lombok.NoArgsConstructor;

@Data

@AllArgsConstructor

@NoArgsConstructor

public class CustomException extends RuntimeException{

private Integer code;//状态码

private String msg;//异常信息

}

第二步在统一异常类GlobalExceptionHandler中添加规则。

package com.hu.handler;

import com.hu.utils.R;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice

public class GlobalExceptionHandler {

//自定义异常

@ResponseBody//为了能够返回数据

@ExceptionHandler(CustomException.class)

public R error(CustomException e){

e.printStackTrace();

return R.error().code(e.getCode()).message(e.getMsg());

}

}

配置阿里云的OSS云存储服务。

官方教程:

安装 (aliyun.com)https://help.aliyun.com/document_detail/32009.html博主仅仅配置了一个文件上传的功能,用来修改和保存头像的。

第一步配置maven依赖:

com.aliyun.oss

aliyun-sdk-oss

3.10.2

第二步在utils工具包写创建AvatarUtils工具类

AvatarUtils工具类代码:

package com.hu.utils;

import com.aliyun.oss.OSS;

import com.aliyun.oss.OSSClientBuilder;

import com.hu.handler.CustomException;

import com.hu.utils.commonResult.ResultCode;

import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.UUID;

public class AvatarUtils {

public static final String defaultAvatarUrl="填默认头像地址";

// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。

private static String endpoint = "";

// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。

private static String accessKeyId = "";

private static String accessKeySecret = "";

// 填写Bucket名称,例如examplebucket。

private static String bucketName = "";

public static String ossUploadAvatar(MultipartFile multipartFile){

String imageUrl=null;

// 创建OSSClient实例。

OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

try {

//获取文件上传的流

InputStream inputStream = multipartFile.getInputStream();

//构建日期目录

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");

String datePath = dateFormat.format(new Date());//日期目录2022/10/10

//获取文件名

String originalFilename = multipartFile.getOriginalFilename();

//随机生成一个文件名

String filename = UUID.randomUUID().toString();

//获取文件后缀名

int i = originalFilename.lastIndexOf(".");

String substring = originalFilename.substring(i);

//判断图片是否符合要求

if (!substring.equals(".jpg")&&!substring.equals(".png"))

{

throw new CustomException(ResultCode.ERROR,"上传图片格式错误,只能是.jpg或者.png");

}

//得到的随机文件名和后缀名拼接成一个新的完整的文件名

String newFilename = filename.concat(substring);

//最后完整的文件路径

String fileUrl = datePath.concat("/").concat(newFilename);

//通过io流将文件传给阿里云的文件存储桶,生成fileUrl这样的一个文件

ossClient.putObject(bucketName, fileUrl, inputStream);

imageUrl = "https://".concat(bucketName).concat(".").concat(endpoint).concat("/").concat(fileUrl);

}catch (Exception ce) {

ce.printStackTrace();

} finally {

if (ossClient != null) {

ossClient.shutdown();

}

}

return imageUrl;

}

}

第三步、通过调用AvatarUtils类下的ossUploadAvatar方法即可获得一个路径,可以选择存在数据库中。

//MultipartFile文件上传类型封装

public Boolean uploadFileByStudent(MultipartFile multipartFile){

String imageUrl = AvatarUtils.ossUploadAvatar(multipartFile);

}

添加MD5加密工具类 ,在utils工具包下新建一个MD5工具类

package com.hu.utils;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

public class MD5Utils {

public static String encrypt(String strSrc) {

try {

char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',

'9', 'a', 'b', 'c', 'd', 'e', 'f' };

//得到加密对象,MD5加密算法只是对字节数组进行加密计算

byte[] bytes = strSrc.getBytes();

//获取MD5加密实例

MessageDigest md = MessageDigest.getInstance("MD5");

// 使用指定的字节更新实例

md.update(bytes);

// 获得密文

bytes = md.digest();

int j = bytes.length;

char[] chars = new char[j * 2];

int k = 0;

// 把每一个byte 做一个与运算

for (int i = 0; i < bytes.length; i++) {

byte b = bytes[i];

chars[k++] = hexChars[b >>> 4 & 0xf];

chars[k++] = hexChars[b & 0xf];

}

return new String(chars);

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

throw new RuntimeException("MD5加密出错!!+" + e);

}

}

public static void main(String[] args) {

System.out.println(MD5Utils.encrypt("111111"));

}

}

redis配置 :

windows下安装redis:

1、下载地址:Releases · microsoftarchive/redis · GitHubhttps://github.com/MicrosoftArchive/redis/releases

2、下载后是个压缩文件,对其解压 

3、解压后可以看到服务、客户端等,选择服务redis-server.exe双击开启。再选择客户端redis-cli.exe双击启动,在客户端输入ping,返回PONG则说明连接成功了

redis整合到项目中

引入redis依赖:

org.springframework.boot

spring-boot-starter-data-redis

配置连接的application.yml文件: 

spring:

redis:

host: 127.0.0.1

port: 6379

测试连接:写个测试方法来进行最基本的连接测试!

@Autowired(required = false)

private RedisTemplate redisTemplate;

@Test

void getName(){

redisTemplate.opsForValue().set("name","huyan!");

System.out.println(redisTemplate.opsForValue().get("name"));

}

运行效果如下!证明Redis连接成功!并且加数据获取数据也成功了! 

权限模块固定写法 :

新建五张表:菜单表;角色表;用户表;菜单角色关系表;角色用户关系表

在maven中导入spring_security和fastjson依赖

org.springframework.boot

spring-boot-starter-security

com.alibaba

fastjson

1.2.62

持续新中~

推荐阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: