参考资料:MybatisPlus官网
环境搭建
创建数据库
CREATE DATABASE `mybatisplus` USE `mybatisplus` CREATE TABLE `user`( id BIGINT(20) NOT NULL COMMENT '主键ID', NAME VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', age INT(11) NULL DEFAULT NULL COMMENT '年龄', email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (id) ); DELETE FROM USER; INSERT INTO USER (id, NAME, age, email) VALUES (1, 'Jone', 18, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com');
数据库名为 mybatisplus,表名为 user
创建一个springboot项目,一个web依赖即可
导入相关maven依赖
mysql
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
Lombok(不是必须品,只是可以偷点懒)
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <optional>true</optional> </dependency>
mybatis-plus
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version> </dependency>
配置application.properties
# mysql spring.datasource.username=root spring.datasource.password=123456 spring.datasource.url=jdbc:mysql://localhost:3306/mybatisplus?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8 # 东8时区,serverTimezone=GMT%2B8 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # 配置日志,方便查看SQL语句 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
实体类Pojo
User
package com.zy.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; }
mapper接口
实现 BaseMapper 接口
UserMapper
package com.zy.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zy.pojo.User; import org.springframework.stereotype.Repository; @Repository //代表持久层 //在对应的mapper上面 继承 基本的接口BaseMapper public interface UserMapper extends BaseMapper<User> { //继承之后,所有的CRUD就完成了 }
主启动类扫描mapper
package com.zy; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //扫描mapper文件夹 @MapperScan("com.zy.mapper") @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
测试查找全部用户
@Test public void select(){ //查询全部用户 List<User> users = userMapper.selectList(null); users.forEach(System.out::println); }
结果