MyBatis-Plus 从入门到上手干事!
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射,而实际开发中,我们都会选择使用 MyBatisPlus,它是对 MyBatis 框架的进一步增强,能够极大地简化我们的持久层代码,下面就一起来看看 MyBatisPlus 中的一些奇淫巧技吧。 说明:本篇文章需要一定的 MyBatis 与 MyBatisPlus 基础。 MyBatis-Plus 官网地址 :https://baomidou.com/ 。 CRUD 使用 MyBatisPlus 实现业务的增删改查非常地简单,一起来看看吧。1.首先新建一个 SpringBoot 工程,然后引入依赖: <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> 2.配置一下数据源: spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver username: root url: jdbc:mysql:///mybatisplus?serverTimezone=UTC password: 123456 3.创建一下数据表: CREATE DATABASE mybatisplus; USE `mybatisplus`; DROP TABLE IF EXISTS `tbl_employee`; CREATE TABLE `tbl_employee` ( `id` bigint(20) NOT NULL, `last_name` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `gender` char(1) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=gbk; insert into `tbl_employee`(`id`,`last_name`,`email`,`gender`,`age`) values (1,'jack','jack@qq.com','1',35),(2,'tom','tom@qq.com','1',30),(3,'jerry','jerry@qq.com','1',40); 4.创建对应的实体类: @Data public class Employee { private Long id; private String lastName; private String email; private Integer age; } 5.编写 Mapper 接口: public interface EmployeeMapper extends BaseMapper<Employee> { } 我们只需继承 MyBatisPlus 提供的 BaseMapper 接口即可,现在我们就拥有了对 Employee 进行增删改查的 API,比如: @SpringBootTest @MapperScan("com.wwj.mybatisplusdemo.mapper") class MybatisplusDemoApplicationTests { @Autowired private EmployeeMapper employeeMapper; @Test void contextLoads() { List<Employee> employees = employeeMapper.selectList