DDL 自动化(DDL自动化(自动建表、索引、列新增、序列))
在启动阶段对扫描实体类,然后实现 DDL 自动化(自动建表、索引、列新增、序列)
1. 引入maven依赖
xml
<dependency>
<groupId>cn.xbatis</groupId>
<artifactId>xbatis-ddl-auto</artifactId>
<version>1.0.1</version>
</dependency>2. spring 容器下的DDL自动化
2.1 springboot Application下DDL自动化
java
@XbatisDDLAutoScan(entityPackages = "com.xxx.entity")
public class ApiApplication {
public static void main(String[] args) {
try {
SpringApplication.run(ApiApplication.class, args);
} catch (Exception e) {
e.printStackTrace();
}
}
}2.2 springboot 开发环境下DDL自动化配置(推荐)
java
@Profile("dev")
@Configuration
@XbatisDDLAutoScan(entityPackages = "com.xxx.entity")
public class XbatisDDLAutoScanConfig {
}只有dev环境才自定建表;其他环境不操作
2.3 XbatisDDLAutoScan属性说明
| 属性名 | 说明 |
|---|---|
| entityPackages | 基础包路径 |
| dbType | 指定数据库类型 |
| mode | NONE,CREATE,UPDATE;默认是 CREATE |
| dataSource | 指定数据源 |
| markerInterface | 指定实体类的父接口 |
3. solon 容器下的DDL自动化配置(yml配置)
yaml
mybatis.db1:
ddlAuto:
- entityPackages: com.**
mode: UPDATE
makerInterface: com.xx.Mysql
dbType: MYSQL
dataSource: xxx
mappers:
- "com.**.mapper.TestMapper"ddlAuto 下配置 dbType、mode、makerInterface、entityPackages;除了entityPackages 其他都是可选的;注意entityPackages要符合solon的目录匹配规则
配置的说明和XbatisDDLAutoScan属性说明一样; 多个逗号分隔!!!
4. 如何配多个?
java
@XbatisDDLAutoScan(entityPackages = "com.xxx.entity")
@XbatisDDLAutoScan(entityPackages = "com.xxx.entity")spring下可以配置多个@XbatisDDLAutoScan注解 solon的配置示例目前就是多个的
5. 多数据源多库如何办?
1. 配置多个配置2. 目录分开或者配置不同的makerInterface3. 不同配置配不同的dataSource
6. 分表处理如何处理
根据实体来,返回多个表名
java
DDLTableNameResolverUtil.set(SysUser.class, tableName -> {
return Arrays.asList(tableName+"_01",tableName+"_02");
})注意:一定要在自动DDL前设置
5. 额外配置示例
java
import cn.xbatis.db.annotations.ColumnDefinition;
import cn.xbatis.db.annotations.Table;
import cn.xbatis.db.annotations.TableId;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Table("sys_user")
@TableDefinition(comment = "PostgreSQL表")
@TableDefinition(dbType=DbType.Name.ORACLE, comment = "ORACLE表")
@Index(name = "idx_sys_user_username", fields = @IndexField(name = "username"))
@Index(
name = "uk_sys_user_username_created_at",
unique = true,
fields = {
@IndexField(name = "username"),
@IndexField(name = "createdAt", direction = IndexDirection.DESC)
}
)
public class SysUser {
@TableId
private Long id;
@ColumnDefinition(length = 64, nullable = false)
private String username;
@ColumnDefinition(precision = 10, scale = 2, defaultValue = "0")
private BigDecimal balance;
private LocalDateTime createdAt;
}@TableDefinition @Index 和 @ColumnDefinition 配置很多,和JPA类似,也更多配置;
