MybatisPlus
MyBatis-Plus官网:MyBatis-Plus 🚀 为简化开发而生
MyBatis是红色小鸟,MyBatis-Plus是蓝色小鸟
-
MyBatisPlus特点:
-
MyBatisPlus是无侵入的,导入MyBatisPlus的依赖之后,仍然可以编写MyBatis的格式操作mapper层。
-
MybatisPlus适合单表的CRUD,如果sql语句很复杂或者涉及到多表,还是要使用MyBatis
-
1. 快速入门
1.1 导入MybatisPlus包
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.3</version>
</dependency>
1.2 自定义Mapper继承BaseMapper
注意指定范型User和数据库的user表
// BaseMapper<>的范型指定为User
public interface UserMapper extends BaseMapper<User> {}
1.3 配置application.yml
spring:datasource:url: jdbc:mysql://192.168.31.20:3306/mp?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghaidriver-class-name: com.mysql.cj.jdbc.Driverusername: mysql8_gtcpassword: gtc123
logging:level:com.itheima: debugpattern:dateformat: HH:mm:ss
#mybatis:
# mapper-locations: classpath*:mapper/*.xml
mybatis-plus:type-aliases-package: com.itehima.mp.domain.po # 别名扫描包mapper-locations: "classpath*:/mapper/**/*.xml"configuration:map-underscore-to-camel-case: truecache-enabled: false # 是否开启二级缓存global-config:db-config:id-type: assign_idupdate-strategy: not_null
1.4 配置启动类
虽然你没有在 Mapper 接口上加 @Mapper
,但你在启动类上用了 @MapperScan
,它会自动扫描并注册所有的 Mapper 接口。
package com.itheima.mp;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@MapperScan("com.itheima.mp.mapper") // mapper扫描包
@SpringBootApplication
public class MpDemoApplication {public static void main(String[] args) {SpringApplication.run(MpDemoApplication.class, args);}}
1.5 使用CRUD
2. 常用注解
如果不符合约定,需要用到对应注解:
3. 常见配置
4. 条件构造器
MyBatisPlus支持各种复杂的where条件。wrapper就是条件。
5. 自定义SQL
6. Service接口