创建数据库和准备用户表
CREATE TABLE `user` (`id` int(8) NOT NULL AUTO_INCREMENT,`name` varchar(20) NOT NULL,`password` varchar(255) NOT NULL,PRIMARY KEY (`id`),UNIQUE KEY `user_name_uindex` (`name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;insert into user values("111","gate","bill");
添加 fastjson 依赖 和 spring boot dev tool 依赖
打开 pom.xml, 在 dependencies 节点下面添加
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.22</version></dependency><!--mybatis-plus依赖--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.2.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId></dependency>
编写UserDo.java
目前 User 只有 id,name,password 三个属性
@Alias(value="UserDo")public class UserDo {private Integer id;private String name;private String password;// 下面是 getter 和 setter 方法。。。}
注意 id 用 Integer 而不用 int, 因为 int 自动初始化为0,mybatis mapper 文件 就不能使用
编写 UserApi.java
@RestController@RequestMapping("/api/user")public class MysqlController {private UserServices userService;@Autowiredpublic MysqlController(UserServices userService) {this.userService = userService;}@GetMapping("/")public Object add() {UserDo user = new UserDo();user.setName("11");user.setPassword("111");user.setId(1);if (userService.findByName(user.getName()) != null) {JSONObject jsonObject = new JSONObject();jsonObject.put("message","用户名已被使用");return jsonObject;}return userService.add(user);}}
api这一层主要是调用service层的方法, 返回JSON数据。我用 @RestController 代替了 @Controller,表示该类里面的方法都是返回 JSON 数据, 而不用再给每个方法添加@ResponseBody注解。add 方法 @PostMapping("") 对应的路由为
POST /api/user
编写 UserServices.java
@Servicepublic class UserServices {private UserMappers userMapper;@Autowiredpublic UserServices(UserMappers userMapper) {this.userMapper = userMapper;}public UserDo add(UserDo user) {userMapper.add(user);return findById(user.getId());}public UserDo findById(int id) {UserDo user = new UserDo();user.setId(id);return userMapper.findOne(user);}public UserDo findByName(String name) {UserDo param = new UserDo();param.setName(name);return userMapper.findOne(param);}}
service这一层处理主要的业务逻辑,比如说添加用户, api层传过来了一个 user对象, 具体怎么添加在这里处理。目前逻辑比较简单,直接调用mapper层的方法,保存到数据库即可。
编写 UserMappers.java
@Repositorypublic interface UserMappers {int add(UserDo user);UserDo findOne(UserDo user);}
一个添加接口和一个查询接口
编写 UserMappers.xml
- 注意替换com.hpm.blog.mapper.UserMappers
注意resultType要填写全路径 ```xml <?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“ >
insert into user(name, password) values (#{name},#{password})
`insert` 标签中的 `useGeneratedKeys` 作用是获取由数据库生成的`id`,注意`mapper xml`文件要和`mapper java`文件同名, 并且包名一致,不同的是xml文件要放在 resource目录之下。xml文件所在的包是一个多级目录结构,要建完一个目录再建另外一个,不能一下子新建一个名为`xxx.yyy.zzz`的目录。到这里, 我们的代码基本写完了。<a name="7m0abt"></a>### 编写`Mybatis`配置文件1. 在 resource目录下面新建一个名为`mybatis.xml` 的文件```xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><settings><!-- 开启驼峰命名转换 Table(create_time) -> Entity(createTime) --><setting name="mapUnderscoreToCamelCase" value="true"/></settings></configuration>
- 打开
application.yml文件, 添加以下内容
- 注意替换com.hpm.blog.model
mybatis:config-location: classpath:mybatis.xmlmapper-locations: classpath:mapper/*.xml
type-aliases-package, 根据你的包结构修改为UserDo.java文件所在的包
- 使
spring boot扫描 mapper文件。打开SpringBootBlogApplication.java, 添加mybatis扫描注解,参数为mapper文件所在的包名
- 注意替换com.hpm.blog.mapper
@MapperScan("com.hpm.blog.mapper")
SpringBootBlogApplication.java内容最终如下
@SpringBootApplication@MapperScan("com.hpm.blog.mapper")public class SpringBootBlogApplication {public static void main(String[] args) {SpringApplication.run(SpringBootBlogApplication.class, args);}}
测试访问接口
代码编写完毕,接下来运行项目,添加一个用户试试。下面使用curl发起一个POST请求。(如果你用的是Windows系统,没有curl这个命令,那么我推荐你安装一个git客户端,用软件带的git bash代替 cmd,将拥有Linux系统下面的包括curl在内的很多有用的命令)。
curl -X POST -H "Content-Type: application/json" -d '{"name": "xiaohong","password": "123456"}' "http://localhost:8080/api/user/"
windows系统下 curl 不能用单引号,要用双引号转义
curl -X POST -H "Content-Type: application/json" -d "{\"name\": \"xiaohong\",\"password\": \"123456\"}" "http://localhost:8080/api/user/"
得到如下输出,添加用户成功。
{"id":10,"name":"xiaohong","password":"123456"}
使用 hash 来保存用户密码
目前为止,数据库中的用户密码还是原文存储的,很不安全,改用 hash 值来存储用户密码。哈希算法很多种,以下使用 SHA-256
打开 UserServices.java 文件
- 修改
add方法
public User add(User user) {String passwordHash = passwordToHash(user.getPassword());user.setPassword(passwordHash);userMapper.add(user);return findById(user.getId());}
- 添加
passwordToHash方法
private String passwordToHash(String password) {try {MessageDigest digest = MessageDigest.getInstance("SHA-256");digest.update(password.getBytes());byte[] src = digest.digest();StringBuilder stringBuilder = new StringBuilder();// 字节数组转16进制字符串// https://my.oschina.net/u/347386/blog/182717for (byte aSrc : src) {String s = Integer.toHexString(aSrc & 0xFF);if (s.length() < 2) {stringBuilder.append('0');}stringBuilder.append(s);}return stringBuilder.toString();} catch (NoSuchAlgorithmException ignore) {}return null;}
重启服务器,再测试一下
curl -X POST -H "Content-Type: application/json" -d "{\"name\": \"xiaoming\",\"password\": \"123456\"}" "http://localhost:8080/api/user/"
输出:
{"id":11,"name":"xiaoming","password":"8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92"}
好了,密码已经由原文存储变为hash存储了。
查看项目完整代码
项目地址: https://github.com/hyrijk/spring-boot-blog
克隆项目到本地
git clone https://github.com/hyrijk/spring-boot-blog.git
checkout 到当前版本
git checkout 324933e88dbf22368b8cc250c57f895fd836e0d8
常见问题
- 可能碰到:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): xiaomingappV1.mapper.UserMapper.findOne问题。
- 看是不是有冲突,路径是否一致.
- Unknown system variable ‘query_cache_size’
- mybatis connection的驱动版本太低不行,更新即可.
- Loading class
com.mysql.jdbc.Driver'. This is deprecated. The new driver class iscom.mysql.cj.jdbc.Driver’. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.- 添加 driver-class-name: com.mysql.cj.jdbc.Driver
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driver
- 添加 driver-class-name: com.mysql.cj.jdbc.Driver
如果报错一堆不知道如何解决
- 项目地址: https://github.com/hyrijk/spring-boot-blog
git clone https://github.com/hyrijk/spring-boot-blog.git
参考资料
- https://juejin.im/post/5de9feb2e51d4558242703be
SpringBoot + Mybatis 教程 : https://blog.csdn.net/Winter_chen001/article/details/80010967
其中可能遇到无法注入的问题,那是因为路径不对,
- https://blog.csdn.net/a532672728/article/details/77702772
- https://juejin.im/post/5de9feb2e51d4558242703be
- https://www.jianshu.com/p/07184349738a
