环境描述
| springboot | 2.6.2 |
| mybatis-plus-boot-starter | 3.5.1 |
| mysql-connector-java | 8.0.11 |
查阅了很多博客,说是使用spring.datasource.schema或者spring.sql.init.schema-locations指定脚本也均无效。不使用启动脚本,启动后在h2控制台,sql可以执行。
sql
- create table tb_vc
- (
- id bigint auto_increment
- primary key,
- name varchar(255) null,
- data varchar(6400) null
- );
多次配置没有用后,最终决定使用类似于springboot加载时创建的方案,具体的mybatis的xml文件的写法
- <update id="createTable">
- create table tb_vc
- (
- id bigint auto_increment
- primary key,
- name varchar(255) null comment,
- data varchar(6400) null comment
- );
- </update>
添加配置类,使用配置类的注解+@PostConstruct解决
- @Configuration
- @Slf4j
- public class InitConfig {
-
-
- @Resource
- private VcMapper vcMapper;
-
- @PostConstruct
- public void init() {
- // todo 你的其他业务逻辑
- vcMapper.createTable();
- }
- }
其他方案:
当然,spring提供了一个接口CommandLineRunner,也可以通过类似的方案
- @SpringBootApplication
- public class VcApplication extends SpringBootServletInitializer implements CommandLineRunner {
-
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
- return application.sources(VcApplication.class);
- }
-
- public static void main(String[] args) throws Exception {
- SpringApplication.run(VcApplication.class, args);
- }
-
-
- @Override
- public void run(String... args) throws Exception {
- logger.info("Application Started !!");
- }
- }