一.资料
二.涉及错误:
a.报错: Project ‘org.springframework.boot:spring-boot-starter-parent’ not found
原因:idea未配置settings.xml文件夹,或者未配置阿里云镜像
b.报错:Error attempting to get column ‘XXX’ from result set. Cause: java.sql.
原因:com.alibaba 的版本问题,切换版本号到1.1.22 即可消除问题
c.报错:Failed to bind properties under 'spring.datasource.type' to java.lang.Class(javax.sql.DataSource)
原因:需要在pom中加入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>
三.操作步骤:
1.创建项目
<groupId>com.markerhub</groupId>
<artifactId>vueblog</artifactId>
打包方式:jar包
注意版本 1.8
勾选developtools--springboot devtools 热加载
勾选developtools--lombok
勾选web--spring web
勾选sql--Mysql Driver
2.删除无关文件夹
只保留:.idea/src/target/HELP.md/pom.xml/vueblog.xml
3.整合mybatis plus
<!-- mp -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<!-- 引入freeMarker的依赖包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- mp代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<!-- mp代码生成器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
4.写配置文件 application.yml
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/vueblog?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
mapper-locations: classpath*:/mapper/**Mapper.xml
server:
port: 8081
5.创建表 m_user 和 m_blog;
CREATE TABLE `m_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(64) DEFAULT NULL,
`avatar` varchar(255) DEFAULT NULL,
`email` varchar(64) DEFAULT NULL,
`password` varchar(64) DEFAULT NULL,
`status` int(5) NOT NULL,
`created` datetime DEFAULT NULL,
`last_login` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `UK_USERNAME` (`username`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `m_blog` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NOT NULL,
`title` varchar(255) NOT NULL,
`description` varchar(255) NOT NULL,
`content` longtext,
`created` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
`status` tinyint(4) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4;
INSERT INTO `vueblog`.`m_user` (`id`, `username`, `avatar`, `email`, `password`, `status`, `created`, `last_login`) VALUES ('1', 'markerhub', 'https://image-1300566513.cos.ap-guangzhou.myqcloud.com/upload/images/5a9f48118166308daba8b6da7e466aab.jpg', NULL, '96e79218965eb72c92a549dd5a330112', '0', '2020-04-20 10:44:01', NULL);
6.创建java类:代码生成工具类 :com.markerhub.CodeGenerator
package com.markerhub;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
// gc.setOutputDir("D:\\test");
gc.setAuthor("关注公众号:MarkerHub");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(null);
pc.setParent("com.markerhub");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("m_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
7.执行CodeGenerator 的main方法,自动生成了controller/entity/service/mapper
8.如果项目报错,则右侧maven侧边栏点击刷新按钮
9.启动项目,输入两个表名
10.在UserController类中添加测试方法
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@GetMapping("/index")
public Object index(){
return userService.getById(1L);
}
}
11.浏览器输入 http://localhost:8081/user/index
收到返回:
{"id":1,"username":"用户名","avatar":"头像","email":"123@163.com","password":"123456","status":1,"created":"2021-04-30T00:45:59","lastLogin":"2021-04-30T00:45:35"}
12.windows系统临时启动redis
(1)下载
(2)下载到目录 D:\Redis-x64-3.0.504
(3临时服务安装 cmd敲命令进入Redis安装文件下,启动临时服务:redis-server.exe redis.windows.conf,如果出现一个方形图标,安装临时服务成功。
进行客户端调用,因为只有临时服务,所以不要关闭上面窗口,我们打开文件夹下redis-cli.exe执行文件,进入客户端Dos窗口,敲入Set uid 1 返回OK ,表示写入内存中;我们再敲 Get uid,会返回一个Value值1
13.登录接口开发
(1)postman 中POST请求 localhost:8081/user/login
{"username":"markethub","password":"111111"}
获取返回的Authorization 是 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIyIiwiaWF0IjoxNjIwNDg5Njg5LCJleHAiOjE2MjEwOTQ0ODl9.5HdkttEBtuDtVviFFfsOB3CIACXRX-xY0Kf22iCxTlDbWY6jp14xPaXtXuGvUsXT4-NZhDhAtzUwiXA0uIHMuA
注意@RequiresAuthentication说明需要登录之后才能访问的接口,其他需要权限的接口可以添加shiro的相关注解。 接口比较简单,我们就不多说了,基本增删改查而已。注意的是edit方法是需要登录才能操作的受限资源。
(2)postman 中POST请求 http://localhost:8081/blog/edit
{"id":2,"title":"这是标题aaa112","description":"这是摘要bbb11","content":"这是内容ccc11"} 在headers中添加 Authorization = eyJ....
此时报错: 类型转换异常,需要将pom.xml文件中的热部署相关的依赖 spring-boot-devtools 删除
测试时,如果id非本人,提示无权编辑
(3)其他链接: get请求:localhost:8081/user/index ,get请求: localhost:8081/blogs