MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
全新的 MyBatis-Plus 3.0 版本基于 JDK8,提供了 lambda 形式的调用,所以安装集成 MP3.0 要求如下:
- JDK 8+
- Maven or Gradle
- Spring Boot 2.5+
- MySql、Oracle、SQLServer、、
一、数据表设计
ID | Name | Sex | Age | Grade |
1 | 小明 | 男 | 12 | 6 |
2 | 小红 | 女 | 11 | 6 |
建表语句如下:
DROP TABLE IF EXISTS `user`;CREATE TABLE `user`
(id BIGINT NOT NULL COMMENT '主键ID',name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',sex VARCHAR(30) NULL DEFAULT NULL COMMENT '性别',age INT NULL DEFAULT NULL COMMENT '年龄',grade VARCHAR(50) NULL DEFAULT NULL COMMENT '年级',PRIMARY KEY (id)
);
然后插入数据:
INSERT INTO `user` (id, name, age, email) VALUES
(1, '小明', '男',12, 6),
(2, '小红', '女',11, 6),
二、开发实例
1、引入依赖
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.5</version><relativePath/></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId><scope>runtime</scope></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-spring-boot3-starter</artifactId><version>3.5.4<version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.26</version></dependency></dependencies>
2、配置数据源
在application.yaml
中配置相关配置信息:
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/Dokerusername: rootpassword: root
3、开发实例
3.1 实体类
@Data
@TableName("`user`")
public class User {@TableId(type = IdType.AUTO)private Long id;@TableField("name")private String name;private String sex;private Integer age;private String grade;
}
TableName:
- 描述:表名注解,标识实体类对应的表
- 使用位置:实体类
TableId:
- 描述:主键注解
- 使用位置:实体类主键字段
TableField:
- 描述:字段注解(非主键)
3.2 UserMapper
接口
<?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" >
<mapper namespace="com.UserMapper">SELECT * FROM `user` WHERE `name` = #{name}
</mapper>
public interface UserMapper extends BaseMapper<User> {@Select("select * from user")List<User> getAllUser();}
3.3 Service层接口
import com.baomidou.mybatisplus.extension.service.IService;// UserService 继承 IService 接口
public interface UserService extends IService<User>{List<User> getAllUser();
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {@Autowiredprivate UserMapper userMapper;public List<User> getAllUser(){return userMapper.getAllUser();}
}
3.4 在 Spring Boot 启动类中添加 @MapperScan
注解,扫描 Mapper 文件夹:
@SpringBootApplication
@MapperScan("com.mapper")
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}