提供一个springboot使用h2数据库是无法使用脚本并报错的处理方案
环境描述
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_incrementprimary key,name varchar(255) null,data varchar(6400) null);
多次配置没有用后,最终决定使用类似于springboot加载时创建的方案,具体的mybatis的xml文件的写法
<update id="createTable">create table tb_vc(id bigint auto_incrementprimary key,name varchar(255) null comment,data varchar(6400) null comment);
</update>
添加配置类,使用配置类的注解+@PostConstruct解决
@Configuration
@Slf4j
public class InitConfig {@Resourceprivate VcMapper vcMapper;@PostConstructpublic void init() {// todo 你的其他业务逻辑vcMapper.createTable();}
}
其他方案:
当然,spring提供了一个接口CommandLineRunner,也可以通过类似的方案
@SpringBootApplication
public class VcApplication extends SpringBootServletInitializer implements CommandLineRunner {@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(VcApplication.class);}public static void main(String[] args) throws Exception {SpringApplication.run(VcApplication.class, args);}@Overridepublic void run(String... args) throws Exception {logger.info("Application Started !!");}
}