MySQL 建表的一些规范
MySQL 建表规范(补充版)
# 1. 添加必要的冗余字段
除了默认的业务表,额外必添加以下6个字段:
id
主键id
**
MySQL
数据库格式:**
`id` BIGINT UNSIGNED NOT NULL COMMENT "主键i",
PRIMARY KEY('id')
** Java
代码格式:**
private Long id;
version
版本号
MySQL
数据库格式:**
`version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT "版本号",`
** Java
代码格式:**
private Integer version;
deleted
删除标记(逻辑删除) => 对用户透明
**
MySQL
数据库格式:**
`deleted` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT "逻辑删除 0=>未删除 1=>删除",
** Java
代码格式:**
private Integer deleted;
user_id_update
更新人
**
MySQL
数据库格式:**
`user_id_update` CHAR(36) NOT NULL COMMENT "更新人id",
** Java
代码格式:
private String userIdUpdate;
time_update
更新时间
**
MySQL
数据库格式:**
`time_update` BIGINT UNSIGNED NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "更新时间戳",
** Java
代码格式:**
private Long timeUpdate;
user_id_create
创建人
**
MySQL
数据库格式:**
`user_id_create\` CHAR(36) NOT NULL COMMENT "创建人",
** Java
代码格式:**
private String userIdCreate;
time_create
创建时间
**
MySQL
数据库格式:**
`time_create` BIGINT UNSIGNED NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "创建时间戳",
** Java
代码格式:**
private Long timeCreate;
根据上述的字段规范,Demo 如下:
------------------------------------------
-- 创建 user 表
------------------------------------------
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
`id` BIGINT UNSIGNED NOT NULL COMMENT "主键id",
`name` VARCHAR(255) NOT NULL COMMENT "姓名",
`age` TINYINT UNSIGNED COMMENT '年龄',
`version` INT UNSIGNED NOT NULL DEFAULT 1 COMMENT "版本号",
`deleted` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT "逻辑删除 0=>未删除 1=>删除",
`user_id_update` CHAR(36) NOT NULL COMMENT "更新人id",
`time_update` BIGINT UNSIGNED NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "更新时间戳",
`user_id_create` CHAR(36) NOT NULL COMMENT "创建人",
`time_create` BIGINT UNSIGNED NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT "创建时间戳",
PRIMARY KEY(`id`)
)engine=innodb default charset=utf8 COMMENT "用户表";
# 2. 基于MyBatis-Plus 的冗余字段设置
MyBatis-Plus 的官方地址:https://baomidou.com/guide/#%E7%89%B9%E6%80%A7
# 2.1 配置定义 ID 生成器
/**
* MyBatis-plus 配置 自定义 ID 生成器
*
* @author chenjintian
*/
@Component
@Slf4j
public class CustomIdGenerator implements IdentifierGenerator {
private LeafSnowflakeApiWrapper leafSnowflakeApiWrapper;
@Autowired
public CustomIdGenerator (LeafSnowflakeApiWrapper leafSnowflakeApiWrapper) {
this.leafSnowflakeApiWrapper = leafSnowflakeApiWrapper;
}
@Override
public Number nextId(Object entity) {
long id = leafSnowflakeApiWrapper.getId();
if (log.isDebugEnabled()) {
log.debug("CustomIdGenerator id:{}.", id);
}
return id;
}
}
public class User {
/**
* 对应数据库的主键id
*/
@TableId(type = IdType.ASSIGN_ID)
private Long id;
}
# 2.2 配置乐观锁和分页插件
@MapperScan("com.ip.profile.service.dao.mapper")
@EnableTransactionManagement
@Configuration
public class MyBatisPlusConfig {
// 注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置单页最大的条数为500条
paginationInterceptor.setLimit(500);
return paginationInterceptor;
}
}
public class User {
/**
* 版本号(乐观锁) =》对用户透明
*/
@Version
private Integer version;
}
# 2.3 配置 更新人、更新时间、创建人、创建时间
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
// 插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
if (log.isDebugEnabled()) {
log.debug("start insert fill ...");
}
long currentTimeStamp = System.currentTimeMillis();
this.setFieldValByName("userIdCreate", UserUtil.getCurrentUserId(), metaObject);
this.setFieldValByName("timeCreate", currentTimeStamp, metaObject);
this.setFieldValByName("userIdUpdate", UserUtil.getCurrentUserId(), metaObject);
this.setFieldValByName("timeUpdate", currentTimeStamp, metaObject);
if (log.isDebugEnabled()) {
log.debug("end insert fill, userIdCreate:{}, timeCreate:{}, userIdUpdate:{}, timeUpdate:{}.",
UserUtil.getCurrentUserId(), currentTimeStamp, UserUtil.getCurrentUserId(), currentTimeStamp);
}
}
// 更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
if (log.isDebugEnabled()) {
log.debug("start update fill ...");
}
long currentTimeStamp = System.currentTimeMillis();
this.setFieldValByName("userIdUpdate", UserUtil.getCurrentUserId(), metaObject);
this.setFieldValByName("timeUpdate", currentTimeStamp, metaObject);
if (log.isDebugEnabled()) {
log.debug("end update fill, userIdUpdate:{}, timeUpdate:{}.", UserUtil.getCurrentUserId(), currentTimeStamp);
}
}
}
public class User {
/**
* 更新人 ID
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private String userIdUpdate;
/**
* 更新时间(自动填充)=》对用户透明
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Long timeUpdate;
/**
* 创建人 ID
*/
@TableField(fill = FieldFill.INSERT)
private String userIdCreate;
/**
* 创建时间(自动填充)=》对用户透明
*/
@TableField(fill = FieldFill.INSERT)
private Long timeCreate;
}
# 2.4 配置逻辑删除
# 逻辑删除
mybatis-plus.global-config.db-config.logic-delete-field=deleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
public class User {
/**
* 删除标记(逻辑删除)=> 对用户透明
*/
@TableLogic
private Integer deleted;
}
# 3. 总结
MyBatis-Plus 帮助开发人员创建主键id,版本号,以及插入时的填充内容(更新人、更新时间、创建人、创建时间),这些工作MyBatis-Plus自动完成,极大的节省开发人员的时间,而且代码会更规范。
补充:添加的Maven的依赖如下:
<!-- MySQL 驱动 + MyBatis-Plus -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>
上次更新: 2023/02/06, 09:35:40