提供一个springboot使用h2数据库是无法使用脚本并报错的处理方案

文章讲述了在SpringBoot2.6.2环境中,如何在不使用启动脚本的情况下,通过MyBatisPlus的XML文件和@Configuration注解的PostConstruct方法,以及CommandLineRunner接口实现数据库表结构的自定义初始化。作者还提及了使用Spring.datasource.schema和spring.sql.init.schema-locations配置无效的情况。

环境描述

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 !!");
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值