MyBatisPlus-核心注解

MyBatisPlus-核心注解

@TableName

如果不使用@TableName注解,实体类的名字就是表名(忽略大小写)

当表名和实体类名不同时,使用@TableName注解,手动指定实体类对应的表名

1
2
3
4
5
6
7
8
@TableName("t_user")
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}

mybatis-plus-global-config-db-config-table-prefix

通过SpringBoot配置文件为所有表添加前缀,这样就不用给每一个实体类配置@TableName注解了

1
2
3
4
5
6
7
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 以控制台输出Sql语句
type-aliases-package: com.xiaobai.pojo # 给实体类起别名
global-config:
db-config:
table-prefix: t_ # 为所有表名前添加前缀

@TableId

当主键的列名和属性名不一致时,我们需要@TableId注解来配置映射

当需要主键策略为MySQL接管时,我们也需要@TableId注解来配置映射(默认是MyBatisPlus接管)

需要注意的是,如果使用雪花算法来生成主键时,主键类型必须为String或者Long类型!!!

  • value属性:配置主键列名
  • type属性:配置主键策略
    • AUTO值:由数据库接管配置主键自增长
    • ASSIGN_ID值:默认值,由MyBatisPlus接管主键的生成(雪花算法)
1
2
3
4
5
6
7
8
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}

mybatis-plus-global-config-db-config-id-type

通过SpringBoot配置文件为所有主键配置主键策略为AUTO,由数据库接管生成主键

1
2
3
4
5
6
7
8
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 以控制台输出Sql语句
type-aliases-package: com.xiaobai.pojo # 给实体类起别名
global-config:
db-config:
table-prefix: t_ # 为所有表名前添加前缀
id-type: auto # 全局设置主键策略为AUTO

自增长主键

当数据表数据特别庞大的时候,需要水平分割数张表,这是如果使用主键自增模式可能会出现主键冲突

所以我们就需要UUID或者雪花算法来生成唯一主键,一般应用于大型分布式项目中


@TableFieId

当非主键的列名和属性名不一致时,我们需要@TableFieId注解来配置映射

想要让MyBatisPlus忽略这个这个属性映射时,我们也要用@TableFieId注解来配置映射

  • value属性:配置列名
  • exist属性:默认为true,则确认该属性是数据库存在的列,配置为false则忽略此属性
1
2
3
4
5
6
7
8
@Data
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}


MyBatisPlus-核心注解
http://blog.170827.xyz/2024/07/04/MyBatisPlus-核心注解/
作者
XIAOBAI
发布于
2024年7月4日
许可协议