Mybatis用了快两年了,在我手上的发展史大概是这样的

第一个阶段

利用Mybatis-Generator自动生成实体类、DAO接口和Mapping映射文件。那时候觉得这个特别好用,大概的过程是这样的

在数据库中先建好表
配置好几个xml文件(一般都是复制粘贴上一个项目的),然后根据数据库中的表,生成实体类、DAO接口和Mapping映射文件
当需要添加数据操作的时候,先在xml中写好CRUD语句,然后在DAO接口层写接口,最后到映射文件
渐渐地,我忽然发现,这种方式越来越烦。改一个字段,要修改很多的配置文件,正常的修改一些查询操作,也需要修改很多已有的配置。

第二个阶段

在学长指导之下,走向了无xml的Mybatis之路。在这个阶段,数据操作的过程大概是这样的

设计需要的实体层
根据实体层,在数据库中建表(非自动建表)
当需要进行增删改查的时候,只需要在Mapper映射文件中,用对应的注解@Select、@Delete等进行相应的操作即可
相比于第一个阶段的使用,在这个阶段脱离了xml的束缚,使用了全注解的形式。但是还是有很多的问题。比如,没有自动生成的代码,所有基础的增删改查都要自己写。如果一个POJO的属性有20个,那你的insert怕是有点长了。

第三个阶段

这个阶段是上一个阶段的扩展,实现了一个通用的mapper,所有的mapper映射都继承这个通用的mapper,就只需要写一些复杂的增删改查就行了

然后就是这篇文章要写的,不需要自己创建数据表,可以根据实体层,自动创建数据表,也就是省去了第二个阶段中的第2步。

这是一个我很喜欢的功能,奈何只在Hibernate中才有。不过在网上搜到一位大佬写的博文,可以实现mybatis自动创建数据表(目前仅限mysql)

该博文涉及的所有代码均已经开源,有特殊修改的可以自己修改相关代码,然后重新打包即可

但是由于这个博文中的内容是基于SpringMvc的,所以附上一份自己修改后的基于SpringBoot的简单Demo(如果项目使用的是SpringMVC,建议去看此框架开发者写的博文)

SpringMvc版本:A.CTable开源框架Mybatis增强自动创建表/更新表结构/实现类似hibernate共通的增删改查

SpringBoot整合A.CTable
项目目录
- com
- config
- MyBatisMapperScannerConfig.java
- TestConfig.java
- entity
- Test.java
- mapper
- TestMapper.java
- DemoApplication.java

依赖包
<dependency>
<groupId>com.gitee.sunchenbin.mybatis.actable</groupId>
<artifactId>mybatis-enhance-actable</artifactId>
<version>1.0.3</version>
</dependency>
application.properties属性配置文件
mybatis.table.auto=update
mybatis.model.pack=com.example.entity
mybatis.database.type=mysql
当mybatis.table.auto=create时,系统启动后,会将所有的表删除掉,然后根据model中配置的结构重新建表,该操作会破坏原有数据。

当mybatis.table.auto=update时,系统会自动判断哪些表是新建的,哪些字段要修改类型等,哪些字段要删除,哪些字段要新增,该操作不会破坏原有数据。

当mybatis.table.auto=none时,系统不做任何处理。

mybatis.model.pack这个配置是用来配置要扫描的用于创建表的对象的包名

Spring配置文件
@Configuration
@ComponentScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.manager.*"})
public class TestConfig {

@Value("${spring.datasource.driver-class-name}")
private String driver;

@Value("${spring.datasource.url}")
private String url;

@Value("${spring.datasource.username}")
private String username;

@Value("${spring.datasource.password}")
private String password;

@Bean
public PropertiesFactoryBean configProperties() throws Exception{
PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
propertiesFactoryBean.setLocations(resolver.getResources("classpath*:application.properties"));
return propertiesFactoryBean;
}

@Bean
public DruidDataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setMaxActive(30);
dataSource.setInitialSize(10);
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestOnBorrow(true);
return dataSource;
}

@Bean
public DataSourceTransactionManager dataSourceTransactionManager() {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource());
return dataSourceTransactionManager;
}

@Bean
public SqlSessionFactoryBean sqlSessionFactory() throws Exception{
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.example.entity.*");
return sqlSessionFactoryBean;
}

}
@Configuration
@AutoConfigureAfter(TestConfig.class)
public class MyBatisMapperScannerConfig {

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() throws Exception{
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.example.mapper.*;com.gitee.sunchenbin.mybatis.actable.dao.*");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
return mapperScannerConfigurer;
}

}
注意MyBatisMapperScannerConfig和TestConfig不能合并,不然会出现@Value为空的错误

实体层
@Table(name = "test")
public class Test extends BaseModel{

private static final long serialVersionUID = 5199200306752426433L;

@Column(name = "id",type = MySqlTypeConstant.INT,length = 11,isKey = true,isAutoIncrement = true)
private Integer id;

@Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 111)
private String name;

@Column(name = "description",type = MySqlTypeConstant.TEXT)
private String description;

@Column(name = "create_time",type = MySqlTypeConstant.DATETIME)
private Date create_time;

@Column(name = "update_time",type = MySqlTypeConstant.DATETIME)
private Date update_time;

@Column(name = "number",type = MySqlTypeConstant.BIGINT,length = 5)
private Long number;

@Column(name = "lifecycle",type = MySqlTypeConstant.CHAR,length = 1)
private String lifecycle;

@Column(name = "dekes",type = MySqlTypeConstant.DOUBLE,length = 5,decimalLength = 2)
private Double dekes;

//省略Setter、Getter

}
属性上的注解定义了创建表时的各个字段的属性

在配置文件中的,com.example.entity.*需要换成自己项目中的实体层目录,com.example.mapper.*需要换成自己项目中的mapper目录

SpringBoot+Mybatis 自动创建数据表(适用mysql)的更多相关文章

  1. springboot项目启动-自动创建数据表

    很多时候,我们部署一个项目的时候,需要创建大量的数据表.例如mysql,一般的方法就是通过source命令完成数据表的移植,如:source /root/test.sql.如果我们需要一个项目启动后, ...

  2. A.CTable 自动创建数据表

    1.添加依赖 <!-- A.CTable 自动创建数据表 --> <dependency> <groupId>com.gitee.sunchenbin.mybati ...

  3. 学习笔记之--Navicat Premium创建数据表

    1.打开Navicat Premium,点击连接,选择MySQL,创建新连接.输入安装MySQL是的用户名和密码.点击确定. 2.admin数据连接已经创建成功.下面为admin新建数据库,输入数据库 ...

  4. MySQL创建数据表

    *  创建数据表 * *       *      一.什么是数据表 * *           * *      二.创建数据表的SQL语句模型 * *          DDL * *       ...

  5. MySQL 创建数据表

    MySQL 创建数据表 创建MySQL数据表需要以下信息: 表名 表字段名 定义每个表字段 语法 以下为创建MySQL数据表的SQL通用语法: CREATE TABLE table_name (col ...

  6. Mysql学习(慕课学习笔记4)创建数据表、查看数据表、插入记录

    创建数据表 Create table [if not exists] table_name(column_name data_type,…….) UNSIGNED 无符号SIGNED 有符号 查看创建 ...

  7. MySQL学习笔记_3_MySQL创建数据表(中)

    MySQL创建数据表(中) 三.数据字段属性 1.unsigned[无符号] 可以让空间增加一倍 比如可以让-128-127增加到0-255 注意:只能用在数值型字段 2.zerofill[前导零] ...

  8. (笔记)Mysql命令create table:创建数据表

    create table命令用来创建数据表. create table命令格式:create table <表名> (<字段名1> <类型1> [,..<字段 ...

  9. MySQL创建数据表并建立主外键关系

    为mysql数据表建立主外键需要注意以下几点: 需要建立主外键关系的两个表的存储引擎必须是InnoDB. 外键列和参照列必须具有相似的数据类型,即可以隐式转换的数据类型. 外键列和参照列必须创建索引, ...

随机推荐

  1. checkstyle+ant生成checkstyle报告

    <?xml version="1.0" encoding="UTF-8" ?> <project name="tibim" ...

  2. You don&#39;t have permission to access &#215;&#215;&#215; on this server.

    之前开发项目一直在linux上用的xampp集成环境,前几天突然想移到window上面去. 開始在window上安装了一个集成环境(名字大概是 Uniform Service),把项目文件已过去, o ...

  3. MySQL 中间层 Atlas MySQL

    Atlas MySQL 详细介绍 Atlas是由 Qihoo 360,  Web平台部基础架构团队开发维护的一个基于MySQL协议的数据中间层项目.它在MySQL官方推出的MySQL-Proxy 0. ...

  4. JavaScript基础 -- 定时器

     js 定时器有以下两个方法: setInterval() :按照指定的周期(以毫秒计)来调用函数或计算表达式.方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭. set ...

  5. linux用于文件解压缩的命令

    1 gzip gzip -<压缩率> 压缩率用数字(1-9)来表示,越大,则压缩率越大. 2 bz2 解压bz2 bzip2 -d filename.bz2

  6. [Codeforces 466C] Number of Ways

    [题目链接] https://codeforces.com/contest/466/problem/C [算法] 维护序列前缀和 , 枚举中间一段即可 , 详见代码 时间复杂度 : O(N) [代码] ...

  7. rsync单向同步

    系统版本:Centos X64 6.4(最小化安装) 先安装依赖包 [root@localhost ~]# yum install vim wget lsof gcc make cmake makec ...

  8. SQLAlchemy 反向生成 model 模型

    前言 Django 反向生成的 model 模型的命令 :  python manager.py inspectdb SQLAlchemy / Flask-SQLAlchemy则是: pip3 ins ...

  9. less新手入门(三) 作为函数使用的Mixin、@import 导入指令 、@import 导入选项

    五.作为函数使用的Mixin 从mixin返回变量 在mixin中定义的所有变量都是可见的,并且可以在调用者的作用范围中使用(除非调用者用相同的名称定义它自己的变量). .mixin(){ @widt ...

  10. 最大化最小值poj2456Aggressive cows

    Aggressive cows Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 15528   Accepted: 7440 ...