MyBatisPlus简介
1.是什么
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
2.为什么
合理封装,简化开发
入门
1.创建数据库
2.创建工程
3.引入依赖
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.atguigu</groupId><artifactId>mybatisplus</artifactId><version>0.0.1-SNAPSHOT</version><name>mybatisplus</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.2.1.RELEASE</spring-boot.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency><!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.0.5</version></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--lombok用来简化实体类--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.2.10.RELEASE</version><configuration><mainClass>com.atguigu.mpdemo.MpdemoApplication</mainClass></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build>
4.创建启动类
@SpringBootApplicationpublic class MybatisPlusApplication {public static void main(String[] args) {SpringApplication.run(MybatisPlusApplication.class,args);}}
5.实现MP
(1)创建实体类
@Datapublic class User {private Long id;private String name;private Integer age;private String email;}
(2) 创建配置文件 application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8spring.datasource.username=rootspring.datasource.password=123123
(3)添加mapper接口
@Repositorypublic interface UserMapper extends BaseMapper<User> {}
(4) 启动类添加注解
@SpringBootApplication@MapperScan("com.atguigu.mybatisplus.mapper")public class MybatisPlusApplication {public static void main(String[] args) {SpringApplication.run(MybatisPlusApplication.class,args);}}
(5) 测试
@SpringBootTestpublic class MybatisPlusApplicationTest {@Autowiredprivate UserMapper userMapper;@Testpublic void getAll(){List<User> users = userMapper.selectList(null);users.forEach(System.out::println);}}
MP配置日志输出
#mybatis日志mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
MP添加信息+主键策略
1.添加用户信息
@Testpublic void addUser(){User user = new User();user.setName("zhang3");user.setAge(33);user.setEmail("zhang3@qq.com");userMapper.insert(user);}
2.主键策略
(1)策略 => 自增 , UUID : 随机字符串 , Redis , MP生成 , AUTO : 自动 , INPUT : 手动输入 , NONE : 不使用 , ID_WORKER : 根据算法生成全局序列(数字) , ID_WORKER_STR : 根据算法生成全局序列(字符串)
3.MP修改数据
@Testpublic void updateUser(){User user = new User();user.setId(1366632417028227073L);user.setName("zhang3UPUP");userMapper.updateById(user);}
4.MP实现自动填充
1修改表字段在User表中添加datetime类型的新的字段 create_time、update_time2、增加实体字段(1)增加字段private Date createTime;private Date updateTime;(2)添加注解@TableField(fill = FieldFill.INSERT)private Date createTime;@TableField(fill = FieldFill.INSERT_UPDATE)private Date updateTime;3、添加控制器@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler {@Overridepublic void insertFill(MetaObject metaObject) {this.setFieldValByName("createTime",new Date(),metaObject);this.setFieldValByName("updateTime",new Date(),metaObject);}@Overridepublic void updateFill(MetaObject metaObject) {this.setFieldValByName("updateTime",new Date(),metaObject);}}
5.乐观锁
MP实现乐观锁
(1)增加字段
数据库增加字段 version
(2)添加注解实现自动填充
@TableField(fill = FieldFill.INSERT)
private Integer version;
(3)添加乐观锁注解
@TableField(fill = FieldFill.INSERT)
private Integer version;
(4)添加插件
@Configuration@EnableTransactionManagement@MapperScan("com.atguigu.mybatisplus.mapper")public class MybatisPlusConfig {/*** 乐观锁插件*/@Beanpublic OptimisticLockerInterceptor optimisticLockerInterceptor() {return new OptimisticLockerInterceptor();}}
(5) 测试
要想用到乐观锁,就必须先实现 => 先查询后修改
@Testpublic void updateUser(){User user = userMapper.selectById(1366652515570946050L);user.setName("wang5");userMapper.updateById(user);}
MP实现基本查询
1.根据id查询
User user = userMapper.selsectById(xxxxxxxx);
2.根据集合查询
public void selectByIds(){List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));users.forEach(System.out::println);}
3.简单查询
@Testpublic void selectByMap(){Map<String,Object> map = new HashMap<>();map.put("name","wang5");map.put("age",55);List<User> users = userMapper.selectByMap(map);users.forEach(System.out::println);}
分页查询
(1)添加插件
/*** 分页插件*/@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}
(2)实现分页
@Testpublic void selectByPage(){Page<User> page = new Page<>(1,3);//IPage<User> userIPage = userMapper.selectPage(page, null);userMapper.selectPage(page, null);List<User> records = page.getRecords();records.forEach(System.out::println);System.out.println(page.getCurrent());System.out.println(page.getPages());System.out.println(page.getSize());System.out.println(page.getTotal());System.out.println(page.hasNext());System.out.println(page.hasPrevious());}
MP实现删除数据
1.根据id删除
@Testpublic void delUser(){int i = userMapper.deleteById(1366652515570946050L);System.out.println(i);}
2.批量删除
@Testpublic void delUsers(){int i = userMapper.deleteBatchIds(Arrays.asList(1366632417028227073L,1366640077500923905L));System.out.println(i);}
逻辑删除
- 物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除的数据
- 逻辑删除:假删除,将数据中代表是否被删除字段修改为”被删除状态”,之后在数据库中仍然能看到此条数据记录
(1) 修改表 添加字段
deleted tinyint 0 (0为存在,1为删除)
(2)添加注解,实现自动填充
@TableField(fill = fieldFill.INSERT)private Integer deleted;this.setFieldValByName("deleted",0,metaObject);
(3)添加逻辑删除注解
@TableLogic@TableField(fill = fieldFill.INSERT)private Integer deleted;
(4) 添加配置
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
(5)添加插件
@Beanpublic ISqlInjector sqlInjector() {return new LogicSqlInjector();}
MP实现条件查询
(1) eq 等于 = eq(“name”, “老王”)—->name = ‘老王’
ne 不等于 <> ne("name", "老王")--->name <> '老王'
(2) ge 等于 >= ge(“age”, 18)--->age >= 18
gt 大于 > gt("age", 18)`--->`age > 18le 小于等于<= le("age", 18)`--->`age <= 18lt 小于 < lt("age", 18)`--->`age < 18
(3) like LIKE ‘%值%’
like("name", "王")--->name like '%王%'
(4) between BETWEEN 值1 AND 值2
between("age", 18, 30)`--->`age between 18 and 30
(5) orderByDesc ORDER BY 字段, … DESC
(6) select 设置查询字段
orderByDesc("id", "name")--->order by id DESC,name DESC
测试
@Testpublic void selectByInfo(){QueryWrapper<User> wrapper = new QueryWrapper<>();// (1) eq、ne//wrapper.eq("name","zhang3");//(2) ge、gt、le、lt//wrapper.ge("age",18);//(3) like//wrapper.like("name","J");//(4) between//wrapper.between("age",18,28);//(5) orderByDescwrapper.orderByDesc("age");//(6) selectwrapper.select("id","name","age");List<User> users = userMapper.selectList(wrapper);users.forEach(System.out::println);}
