SpringBoot+Mybatis 自动创建数据表

方法一:https://www.jianshu.com/p/25db002b0367 (在我的项目中出现冲突,无法访问自己写的mapper.xml)

方法二:

第一步:

  • SpringBoot启动项
    @EnableScheduling
    @SpringBootApplication
    /*若要自动生成表需先将@ComponentScan注释以及application.properties中的执行初始化数据部分*/
    @ComponentScan(basePackages = {"com.springboot.base.module","com.gitee.sunchenbin.mybatis.actable.manager","com.springboot.base.common","com.springboot.base.filters","com.springboot.base.handlers"})
    @MapperScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.dao"})
    public class SpingbootApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(SpingbootApplication.class, args);
    	}
    
    }

     

在启动项文件中添加注解@ComponentScan 引入项目中需要注入的类以及ACTable的启动类路径"com.gitee.sunchenbin.mybatis.actable.manager"

另外需要配置注解@MapperScan(basePackages = {"com.gitee.sunchenbin.mybatis.actable.dao"})引入ACTable的dao层

第二步:

@Configuration
public class PropertiesConfig {

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

}

创建一个配置类,引入方法名为configProperties的bean。主要是为了ACTable中读取变量

 第三步:

application.properties属性配置文件

mybatis.table.auto=update
mybatis.model.pack=com.example.entity
mybatis.database.type=mysql
#配置.xml文件路径
mybatis.mapper-locations=classpath*:mapper/*.xml,classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml

classpath*:mapper/*.xml为自己的项目xml路径。
当mybatis.table.auto=create时,系统启动后,会将所有的表删除掉,然后根据model中配置的结构重新建表,该操作会破坏原有数据。

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

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

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

  • 引入依赖包
//maven格式

    com.gitee.sunchenbin.mybatis.actable
    mybatis-enhance-actable
    2.1.5



//gradle格式
dependencies {
    implementation('tk.mybatis:mapper-spring-boot-starter:2.1.5')
}

 

你可能感兴趣的:(SpringBoot+Mybatis 自动创建数据表)