mybatis-plus自带了mybatis,所以不用重复导入了
Mybatis-Plus查单表比较方便,而且还写好了常用的的查询语句,可以直接使用
创建数据库:
CREATE DATABASE `security` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
创建表:
CREATE TABLE user (
id int unsigned auto_increment,
username varchar(32) NOT NULL,
password varchar(32) NOT NULL,
PRIMARY KEY (id)
);
插入表数据:
insert into user(id,username,password) values('1','root','root');
insert into user(id,username,password) values('2','admin','admin');
insert into user(id,username,password) values('3','jack','123456');
查询表:
select * from user;
SpringBoot 连接MySql配置 JDBC5:
导入Jar包,SpringBoot3.0 以下:
mysql
mysql-connector-java
5.1.49
com.baomidou
mybatis-plus-boot-starter
3.5.2
application.properties连接MySql数据库配置:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/db_name?useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
entity层:
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
// mybatis-plus
@TableName(value = "user")
public class User {
// IdType.ASSIGN_ID 雪花算法
@TableId(value = "id", type = IdType.ASSIGN_ID)
private String id;
// exist = true 数据表中存在该字段
@TableField(value = "username", exist = true)
// 非空约束
@NonNull
private String username;
@TableField(value = "password", exist = true)
@NonNull
private String password;
// 传给前端的日期格式
@JsonFormat(pattern = "yyyy年MM月dd日 HH:mm:ss",timezone="Asia/Shanghai")
private Date createTime;
}
Dao层:
@Mapper
public interface UserDao extends BaseMapper {}
Service层:
@Service
public class UserServiceImpl {
@Autowired
UserDao userDao;
}
使用测试类进行测试:
@Test
public void testInsertUser() {
userService.addUser(new User(null, "lisi", "123456"));
}
controller层:
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserServiceImpl userService;
@PostMapping()
public String addUser(HttpServletRequest request, User user) {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
} else {
}
if (userService.findUser(user.getUsername()) != null) {
return Result.failGetString("用户名已存在");
} else {
int result = userService.addUser(user);
return Result.okGetString("插入成功",user);
}
}
@DeleteMapping()
public String delUser(HttpServletRequest request, User user) {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
} else {
}
String message = userService.delUserById(user.getId());
if (message.equals("1")) {
return Result.okGetString("删除成功",user);
} else if (message.equals("0")) {
return Result.failGetString("删除失败 原因:没有找到该用户的编号");
} else {
return Result.failGetString("删除失败");
}
}
@PutMapping()
public String updateUser(HttpServletRequest request, User user) {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
} else {
}
int message = userService.updateUserById(user);
if (message == 1) {
return Result.okGetString("更新成功",user);
} else {
return Result.failGetString("更新失败");
}
}
}
后端返回的模板:
{
"code": 0,
"msg": "success",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtb2JpbGUiOiIxODI4OTQ1NDg0NiIsInZlcl9jb2RlIjoi8J6Jg CIsImV4cCI6MTY4NTMzMDk4OCwiaXNzIjoicHJvOTExIn0.zb_ZL6JohYkHdUwQp7678SqiwFpuxpBhBtdsS7L1k1w",
"name":"张三",
"age":36
}
}
在test/com/cy/store/StoreApplicationTests.java下编写测试类,查看MySql是否连接成功:
@Test
void getConnection() throws SQLException {
Connection connection = dataSource.getConnection();
System.out.println("connection=" + connection);
// HikariProxyConnection 默认连接池
}
mybatis-plus的逻辑删除:
mybatis-plus.global-config.db-config.logic-delete-field=is_delete
mybatis-plus.global-config.db-config.logic-not-delete-value=0
mybatis-plus.global-config.db-config.logic-delete-value=1
# id自增
mybatis-plus.global-config.db-config.id-type=auto
开启debug日志:
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
开启分页查询的total的配置类:
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mpi = new MybatisPlusInterceptor();
mpi.addInnerInterceptor(new PaginationInnerInterceptor());
return mpi;
}
}
分页查询的案例:
@Override
public ResponseResult hotArticleList() {
// 条件
LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>();
wrapper.eq(Article::getStatus, 0);
wrapper.orderByDesc(Article::getViewCount);
// 分页
Page page = new Page<>(0, 10);
// 结果
Page result = page(page, wrapper);
return ResponseResult.success(result);
}
分页查询,开启total/count目标行数: