SpringBoot+Mybatis 自动创建数据表

MybatisHibernate是两个比较热门的持久层框架。使用起来也各有利弊(个人使用了几个月的Hibernate后还是决定回到Mybatis的怀抱)

《SpringBoot+Mybatis 自动创建数据表》

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

第一个阶段

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

  1. 在数据库中先建好表
  2. 配置好几个xml文件(一般都是复制粘贴上一个项目的),然后根据数据库中的表,生成实体类DAO接口Mapping映射文件
  3. 当需要添加数据操作的时候,先在xml中写好CRUD语句,然后在DAO接口层写接口,最后到映射文件

渐渐地,我忽然发现,这种方式越来越烦。改一个字段,要修改很多的配置文件,正常的修改一些查询操作,也需要修改很多已有的配置。

第二个阶段

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

  1. 设计需要的实体层
  2. 根据实体层,在数据库中建表(非自动建表)
  3. 当需要进行增删改查的时候,只需要在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;
    }

}

注意MyBatisMapperScannerConfigTestConfig不能合并,不然会出现@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目录

Github源码地址:
https://github.com/zyf970617/mybatis-auto-create-table

要是对你有用就点个赞把~

    原文作者:徐森威
    原文地址: https://www.jianshu.com/p/25db002b0367
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞