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. poj 3263 Tallest Cow(线段树)

    Language: Default Tallest Cow Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 1964   Ac ...

  2. DBCP,C3P0,Tomcat_JDBC 性能及稳定性測试

    原创文章,转载请指明出处:http://aub.iteye.com/blog/1404219, 尊重他人即尊重自己 DBCP,C3P0,Tomcat_JDBC 性能及稳定性測试 1.測试环境: 硬件环 ...

  3. mac终端配置Android ADB命令

    不得不说mac是一款开发利器,不仅可以开发ios,而且对于Android开发也是不错的选择,下面我就对mac配置adb命令,进行简要的说明.下面我将一下mac环境下的配置步骤:1.在自己的目录(hom ...

  4. Codeforces Round #319 (Div. 2) C. Vasya and Petya's Game 数学题

                                                     C. Vasya and Petya's Game                           ...

  5. linux select poll and epoll

    这里以socket文件来阐述它们之间的区别,假设现在服务器端有100 000个连接,即已经创建了100 000个socket. 1 select和poll 在我们的线程中,我们会弄一个死循环,在循环里 ...

  6. beego1---beego,bee环境配置

    1.配置环境变量GOPATH(代码路径,先在里面建立src,pkg,bin3个目录),GOROOT:go安装的目录,go安装目录下的bin目录放到Path环境变量. 安装完bee工具之后,bee 可执 ...

  7. Email-ext plugin

    https://wiki.jenkins.io/display/JENKINS/Email-ext+plugin General This plugin extends Jenkins built i ...

  8. Oracle利用游标返回结果集的的例子(C#)...(最爱)

    引用地址:http://www.alixixi.com/program/a/2008050727634.shtml   本例在VS2005+Oracle 92010 + WindowsXp Sp2测试 ...

  9. uva11149

    Consider an n-by-n matrix A. We define Ak = A ∗ A ∗ . . . ∗ A (k times). Here, ∗ denotes the usual m ...

  10. java笔记线程方式1获取对象名称

    * 如何获取线程对象的名称呢? * public final String getName():获取线程的名称. * 如何设置线程对象的名称呢? * public final void setName ...