1. 痛点
我们在使用Mybatis或Mybatis-Plus时,可以用其自带的generator插件根据已经存在的数据库表生成代码(包括实体类),但是却不能通过实体类来创建、更改表。如果你使用的是JPA,那不必烦恼,JPA有此功能。使用Mybatis系列的可以考虑使用ACTable。
2. ACTable介绍
官网复制的介绍:A.C.Table是对Mybatis做的增强功能,支持SpringBoot以及传统的SpringMvc项目结构,简单配置即可,该框架是为了能够使习惯了hibernate框架的开发者能够快速的入手Mybatis, “A.C.Table” 本意是自动建表的意思,A.C.Table是一个基于Spring和Mybatis的Maven项目,增强了Mybatis的功能,过配置model注解的方式来创建表,修改表结构,并且实现了共通的CUDR功能提升开发效率,同时能够兼容tk.mybatis和mybatis-plus,如需使用依赖相关的pom依赖即可,目前仅支持Mysql,后续会扩展针对其他数据库的支持。
3. 使用方式
先引入依赖(已经有了mysql支持和Mybatis),如果没有mysql和Mybatis请自行引入。
<!-- 生成表依赖-->
<dependency>
<groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
<artifactId>mybatis-enhance-actable</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
配置文件中进行配置
#配置模板
# actable的配置信息
actable.table.auto=update
actable.model.pack=com.yours.model
actable.database.type=mysql
actable.index.prefix=自己定义的索引前缀#该配置项不设置默认使用actable_idx_
actable.unique.prefix=自己定义的唯一约束前缀#该配置项不设置默认使用actable_uni_
# mybatis自有的配置信息,key也可能是:mybatis.mapperLocations
mybatis.mapper-locations=classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml
我的配置:
#自动建表模式,选择更新模式
mybatis.table.auto=update
#要扫描的实体类路径
mybatis.model.pack=com.study.vue.entity
#数据库类型,目前只支持mysql
mybatis.database.type=mysql
#要用到的xml路径,固定的
mybatis.mapper-locations=classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml
配置信息解释:
springboot2.0+启动类需要做如下配置(必备)
1.@ComponentScan配置,路径"com.gitee.sunchenbin.mybatis.actable.manager.*"
2.@MapperScan配置,路径"com.gitee.sunchenbin.mybatis.actable.dao.*"
@MapperScan({"com.gitee.sunchenbin.mybatis.actable.dao.*"} )
@ComponentScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.manager.*"})
创建完成后进入数据库查看:
@Table("t_user") //创建表时的表名,不指定名称时默认为类名
public class User {
//字段注解,不指定名称时默认为字段名,会将驼峰字段用_分割
@Column(name = "id",type = MySqlTypeConstant.INT,isKey = true,isAutoIncrement = true)
private Integer id;
@Column(name = "name",type = MySqlTypeConstant.VARCHAR)
private String name;
@Column(name = "phone",type = MySqlTypeConstant.VARCHAR)
private String phone;
@Column(name = "create_time",type = MySqlTypeConstant.DATE)
private Date createTime;
@Column(name = "del",type = MySqlTypeConstant.BIT,defaultValue = "0")
private Boolean del;
}
@Table
public class Dept {
@Column(type = MySqlTypeConstant.INT)
@IsKey //主键,相当于isKey = true
@IsAutoIncrement //自增,相当于isAutoIncrement = true
private Integer id;
@Column
private Integer pid;
@Column
private String name;
@Column
private LocalDateTime createTime;
@Column
private Boolean del;
}