1.MybatisPlus的起步依赖
MyBatisPlus官方提供了starter,其中集成了Mybatis和MybatisPlus的所有功能,并且实现了自动装配效果。
因此我们可以用MybatisPlus的starter代替Mybatis的starter:
<!--MybatisPlus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
2.定义Mapper
自定义的Mapper继承MybatisPlus提供的BaseMapper接口:
public interface UserMapper extends BaseMapper<User> {
}
MyBatisPlus通过扫描实体类,并基于反射获取实体类信息作为数据库表信息
@Data
//可以省略get和set的所有方法简便
public class User {
private Long id;
private String username;
private String password;
private String phone;
private String info;
private Integer status;
private Integer balance;
private LocalDateTime createTime;
private LocalDateTime updateTime;
}
/*
类名驼峰转下划线作为表明
名为id的字段作为主键
变量名驼峰转下划线作为表的字段名
*/
MybatisPlus中比较常用的几个注解如下:
•@TableName:用来指定表名
•@TableId:用来指定表中的主键字段信息
•@TableField:用来指定表中的普通字段信息
IdType枚举:
AUTO:数据库自增长
INPUT:通过set方法自行输入
ASSIGN_ID:分配 ID,接口IdentifierGenerator的方法nextId来生成id,默认实现类为DefaultIdentifierGenerator雪花算法
使用@TableField的常见场景:
成员变量名与数据库字段名不一致
成员变量名以is开头,且是布尔值
成员变量名与数据库关键字冲突
成员变量不是数据库字段
MyBatisPlus的配置项继承了MyBatis原生配置和一些自己特有的配置。例如
mybatis-plus:
type-aliases-package: com.itheima.mp.domain.po # 别名扫描包
mapper-locations: "classpath*:/mapper/**/*.xml" # Mapper.xml文件地址,默认值
configuration:
map-underscore-to-camel-case: true # 是否开启下划线和驼峰的映射
cache-enabled: false # 是否开启二级缓存
global-config:
db-config:
id-type: assign_id # id为雪花算法生成
update-strategy: not_null # 更新策略:只更新非空字段
id-type: assign_id # id为雪花算法生成
update-strategy: not_null # 更新策略:只更新非空字段