一、快速开始
1. 创建数据库
mybatis-plus
DROP TABLE IF EXISTS user ;
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' ) ;
2. 新建项目
2.1 POM
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
</ dependency>
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> mybatis-plus-boot-starter</ artifactId>
< version> 3.0.5</ version>
</ dependency>
2.2 YML
spring.datasource.driver- class- name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc: mysql: //192.168.91.132: 3306/mybatis- plus? useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
2.3 User
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
2.4 UserMapper
@Repository
public interface UserMapper extends BaseMapper < User > {
}
2.5 主启动
@SpringBootApplication
@MapperScan ( "com.qs.mybatis_plus.mapper" )
public class MybatisPlusApplication {
public static void main ( String [ ] args) {
SpringApplication . run ( MybatisPlusApplication . class , args) ;
}
}
3. 配置日志
3.1 YML
mybatis- plus.configuration.log- impl=org.apache.ibatis.logging.stdout.StdOutImpl
二、CRUD 接口
1. 插入操作
1.1 @TableId
@TableId(type = IdType.AUTO)
:主键自增 @TableId(type = IdType.NONE)
:未设置主键 @TableId(type = IdType.INPUT)
:手动输入 @TableId(type = IdType.ID_WORKER)
:雪花算法 @TableId(type = IdType.UUID)
:UUID @TableId(type = IdType.ID_WORKER_STR)
:ID_WORKER 字符串表示法
1.2 主键生成策略
snowflake 是 Twitter 开源的 分布式 ID 生成算法,结果是一个 long 型的 ID。 其核心思想是:
使用 41bit 作为毫秒数。 10bit 作为机器的 ID(5个bit 是数据中心,5个bit 的机器ID)。 12bit 作为毫秒内的流水号(意味着每个节点,在每毫秒可以产生 4096 个ID)。 最后还有一个符号位,永远是0。
2. 自动填充
2.1 数据库加字段
gmt_created:自动填充 gmt_create_time:自动填充 gmt_modified gmt_update_time
2.2 User
@TableField ( fill = FieldFill . INSERT )
private Date createTime;
@TableField ( fill = FieldFill . INSERT_UPDATE )
private Date updateTime;
2.3 MyMetaObjectHandler
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill ( MetaObject metaObject) {
this . setFieldValByName ( "createTime" , new Date ( ) , metaObject) ;
this . setFieldValByName ( "updateTime" , new Date ( ) , metaObject) ;
}
@Override
public void updateFill ( MetaObject metaObject) {
this . setFieldValByName ( "updateTime" , new Date ( ) , metaObject) ;
}
}
3. 乐观锁
乐观锁: 故名思意 十分乐观,它总是认为不会出现问题。 无论干什么不去上锁,如果出现了问题,再次更新值测试。 悲观锁: 故名思意 十分悲观,它总是认为总是出现问题。 无论干什么都会上锁,再去操作。
3.1 数据库加字段
version:版本
3.2 User
@Version
private Integer version;
3.3 MybatisPlusConfig
@Configuration
@EnableTransactionManagement
@MapperScan ( "com.qs.mybatis_plus.mapper" )
public class MybatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor ( ) {
return new OptimisticLockerInterceptor ( ) ;
}
}
4. 分页查询
4.1 MybatisPlusConfig
@Bean
public PaginationInterceptor paginationInterceptor ( ) {
return new PaginationInterceptor ( ) ;
}
5. 逻辑删除
物理删除:从数据库中直接移除。 逻辑删除:数据库中没有被移除,而是通过一个变量来让他失效。 deleted = 0 => deleted = 1。
5.1 数据库加字段
5.2 User
@TableLogic
private Integer deleted;
5.3 MybatisPlusConfig
@Bean
public ISqlInjector sqlInjector ( ) {
return new LogicSqlInjector ( ) ;
}
5.4 YML
mybatis- plus.global- config.db- config.logic- delete- value=1
mybatis- plus.global- config.db- config.logic- not- delete- value=0
6. 性能分析
6.1 MybatisPlusConfig
@Bean
@Profile ( { "dev" , "test" } )
public PerformanceInterceptor performanceInterceptor ( ) {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor ( ) ;
performanceInterceptor. setMaxTime ( 500 ) ;
return performanceInterceptor;
}
6.2 YML
spring.profiles.active=dev
7. 代码生成器
7.1 POM
< dependency>
< groupId> com.baomidou</ groupId>
< artifactId> mybatis-plus-generator</ artifactId>
< version> 3.0.5</ version>
</ dependency>
< dependency>
< groupId> org.apache.velocity</ groupId>
< artifactId> velocity-engine-core</ artifactId>
< version> 2.3</ version>
</ dependency>
7.2 CodeAutoGenerator
public class CodeAutoGenerator {
public static void main ( String [ ] args) {
AutoGenerator mpg = new AutoGenerator ( ) ;
GlobalConfig gc = new GlobalConfig ( ) ;
String projectPath = System . getProperty ( "user.dir" ) ;
gc. setOutputDir ( projectPath + "/src/main/java" ) ;
gc. setAuthor ( "qs" ) ;
gc. setOpen ( false ) ;
gc. setFileOverride ( true ) ;
gc. setIdType ( IdType . ID_WORKER ) ;
gc. setDateType ( DateType . ONLY_DATE ) ;
gc. setSwagger2 ( true ) ;
mpg. setGlobalConfig ( gc) ;
DataSourceConfig dsc = new DataSourceConfig ( ) ;
dsc. setDbType ( DbType . MYSQL ) ;
dsc. setDriverName ( "com.mysql.cj.jdbc.Driver" ) ;
dsc. setUrl ( "jdbc:mysql://192.168.91.132:3306/mybatis-plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8" ) ;
dsc. setUsername ( "root" ) ;
dsc. setPassword ( "123456" ) ;
mpg. setDataSource ( dsc) ;
PackageConfig pc = new PackageConfig ( ) ;
pc. setParent ( "com.qs" ) ;
pc. setModuleName ( "learn" ) ;
pc. setEntity ( "entity" ) ;
pc. setMapper ( "mapper" ) ;
pc. setService ( "service" ) ;
pc. setController ( "controller" ) ;
mpg. setPackageInfo ( pc) ;
StrategyConfig strategy = new StrategyConfig ( ) ;
strategy. setInclude ( "role" , "permissions" ) ;
strategy. setNaming ( NamingStrategy . underline_to_camel) ;
strategy. setColumnNaming ( NamingStrategy . underline_to_camel) ;
strategy. setEntityLombokModel ( true ) ;
strategy. setLogicDeleteFieldName ( "deleted" ) ;
TableFill gmtCreated = new TableFill ( "gmt_created" , FieldFill . INSERT ) ;
TableFill gmtCreateTime = new TableFill ( "gmt_create_time" , FieldFill . INSERT ) ;
TableFill gmtModified = new TableFill ( "gmt_modified" , FieldFill . INSERT_UPDATE ) ;
TableFill gmtUpdateTime = new TableFill ( "gmt_update_time" , FieldFill . INSERT_UPDATE ) ;
ArrayList < TableFill > tableFills = new ArrayList < > ( ) ;
tableFills. add ( gmtCreated) ;
tableFills. add ( gmtCreated) ;
tableFills. add ( gmtCreateTime) ;
tableFills. add ( gmtModified) ;
tableFills. add ( gmtUpdateTime) ;
strategy. setTableFillList ( tableFills) ;
strategy. setVersionFieldName ( "version" ) ;
strategy. setRestControllerStyle ( true ) ;
strategy. setControllerMappingHyphenStyle ( true ) ;
mpg. setStrategy ( strategy) ;
mpg. execute ( ) ;
}
}