在Spring Boot中Mybatis-Plus使用记录
详细教程参见 Mybatis-Plus官网
1. 依赖
在springboot项目中加入这两个依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>
2. 数据库建立
建表语句
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL COMMENT '主键ID',
`name` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
`email` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '邮箱',
`valid` int(10) NULL DEFAULT NULL COMMENT '是否存在',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'Jone', 18, 'test1@baomidou.com', 1);
INSERT INTO `user` VALUES (2, 'Jack', 20, 'test2@baomidou.com', 1);
INSERT INTO `user` VALUES (3, 'Tom', 28, 'test3@baomidou.com', 1);
INSERT INTO `user` VALUES (4, 'Sandy', 21, 'test4@baomidou.com', 0);
INSERT INTO `user` VALUES (5, 'Billie', 24, 'test5@baomidou.com', 0);
SET FOREIGN_KEY_CHECKS = 1;
3. application.yml文件配置
# 数据库连接的配置
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 1234
url: jdbc:mysql://localhost:3306/mybatisplus?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf-8
# 逻辑删除配置,当字段为1是为存在,当为0时表示删除
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag
logic-not-delete-value: 1
logic-delete-value: 0
# 这个配置是为了打印数据库查询语句
logging:
level:
com.huo.mybatisplus.mapper: debug
4. Entity实体类
import com.baomidou.mybatisplus.annotation.TableLogic;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email
@TableLogic //逻辑删除字段
private String valid;
}
5. Mapper接口的开发(UserMapper.java)
!!!千万不要忘记在springboot的启动类添加注解@MapperScan(“com.mybatisplus.mapper”),其中的值是mapper的包
首先要继承BaseMapper这个类,这个类中提供了许多默认的查询方法,基本上简单的查询就不需要写了。
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.huo.mybatisplus.entity.User;
public interface UserMapper extends BaseMapper<User> {
}
6. Service层的开发
这里一定要继承IService这个类
接口中要继承IService这个类,实现类中要继承ServiceImpl这个类并实现IUserService这个接口
//接口
public interface IUserService extends IService<User> {
}
//实现类
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
}
7.测试类
@SpringBootTest
class DemoApplicationTests {
@Autowired
IUserService userService;
@Test
void delete() {
userService.remove(new QueryWrapper<User>().gt("id", 3));
}
}
这里我只写了remove方法,其他保存功能等都在官网有写到CRUD接口,都可以调用一下试试