Spring Boot菜鸟示例——MyBatis-plus简单示例
创建数据库MP
与表User
并添加字段
// 创建数据库 略
// 创建表
CREATE TABLE Test.`User` (
id INT auto_increment NOT NULL COMMENT '自增主键',
name varchar(100) NULL COMMENT '姓名',
password varchar(100) NULL COMMENT '密码',
account varchar(100) NOT NULL,
CONSTRAINT User_PK PRIMARY KEY (id),
CONSTRAINT User_UN UNIQUE KEY (account)
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8mb4
COLLATE=utf8mb4_0900_ai_ci;
// 添加数据条
-- Auto-generated SQL script #202207052210
INSERT INTO Test.`User` (name,password,account)
VALUES ('hiyj1','123456','hiyj1acc');
INSERT INTO Test.`User` (name,password,account)
VALUES ('hiyj2','654321','hiyj2acc');
项目结构
额外的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>compile</scope>
</dependency>
重命名application.properties
配置文件为application.yml
格式,更好用,并添加mysql
配置信息
server:
port: 8888
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.NonRegisteringDriver
type: com.alibaba.druid.pool.DruidDataSource
# 主要
url: jdbc:mysql://127.0.0.1/Test
# 主要
username: root
# 主要
password: root
# 下边的一些其他参数,照抄就行
filters: stat
initialSize: 2
maxActive: 300
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: false
maxPoolPreparedStatementPerConnectionSize: 200
编写User类,用来对应数据库的表信息
import lombok.Data;
import java.io.Serializable;
// 自动添加get\set\toString方法
@Data
// 实现序列化,方便直接将对象转成字符串发出去
public class User implements Serializable {
private int id;
private String account;
private String name;
private String password;
}
编写Mybatis-plus
的UserMapper
接口,用来查询数据库的
// Mybatis-plus包,需要添加依赖
import cn.hiyj.mp.mpex.object.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
// @Mapper声明这个接口是一个Mapper,会自动交给Spring Boot框架管理这个接口
@Mapper
public interface UserMapper {
// 获取所有User,自动将一行一行的数据生成User对象并返回List<User>
@Select("select * from user")
List<User> getUsers();
// 根据user的account查找User,@Param("user"),表示传入的参数命名为user在sql中使用
// #{user.account},获取@Param("user")传来的user对象的account属性
@Select("select * from user where account = #{user.account}")
User findUser(@Param("user") User user);
}
编写Controller
层UserController
代码
package cn.hiyj.mp.mpex.controller;
import cn.hiyj.mp.mpex.mapper.UserMapper;
import cn.hiyj.mp.mpex.object.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "user")
public class UserController {
private UserMapper userMapper;
// @Autowired可以直接加到变量头上,但是会有黄线
// @Autowired可以从Spring Boot框架管理的Bean中直接获取,不用自己初始化
// Spring Boot框架管理的Bean,可以通过添加注解来添加,例如@Mapper、@RestController等这类的都会由
// Spring Boot框架管理这些Bean,不过一般的类有其他的注解,@Mapper、@RestController这几个是有专用功能的
@Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
// 获取对象列表,会自动转为json格式字符串
@GetMapping(value = "getUsers")
public List<User> getUsers() {
return userMapper.getUsers();
}
@PostMapping(value = "login")
public String login(@RequestBody User user) {
//直接通过Mapper接口查询
User search = userMapper.findUser(user);
if (search == null) {
return "用户不存在";
} else if (search.getPassword().equals(user.getPassword())) {
return "登录成功";
} else {
return "密码错误";
}
}
}
运行测试
账户1:hiyj1acc 密码:123456
账户12:hiyj2acc 密码:654321
curl http://localhost:8888/user/getUsers
curl -X POST -H "Content-Type: application/json" -d"{\"account\":\"hiyj1acc\",\"password\": \"123456\"}" http://localhost:8888/user/login
curl -X POST -H "Content-Type: application/json" -d"{\"account\":\"hiyj1acc\",\"password\": \"654321\"}" http://localhost:8888/user/login
curl -X POST -H "Content-Type: application/json" -d"{\"account\":\"hiyj2acc\",\"password\": \"654321\"}" http://localhost:8888/user/login