欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot2.X后配置自动执行schema.sql无效

程序员文章站 2022-04-30 15:19:00
...

使用mybatis-plus进行初始化h2数据库,发现无法识别sql以下是错误日志
错误日志:

2021-06-30 22:42:24.792 ERROR 13956 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Error thrown while acquiring connection from data source
org.h2.jdbc.JdbcSQLSyntaxErrorException: Schema "classpath:db/schema-h2.sql" not found [90079-200]
	at org.h2.message.DbException.getJdbcSQLException(DbException.java:576) ~[h2-1.4.200.jar:1.4.200]
	at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ~[h2-1.4.200.jar:1.4.200]
	at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.200.jar:1.4.200]
	at org.h2.message.DbException.get(DbException.java:181) ~[h2-1.4.200.jar:1.4.200]
	at org.h2.engine.Database.getSchema(Database.java:1936) ~[h2-1.4.200.jar:1.4.200]
	at org.h2.engine.Session.setCurrentSchemaName(Session.java:1435) ~[h2-1.4.200.jar:1.4.200]
	at org.h2.jdbc.JdbcConnection.setSchema(JdbcConnection.java:1941) ~[h2-1.4.200.jar:1.4.200]
	at com.zaxxer.hikari.pool.PoolBase.setupConnection(PoolBase.java:427) ~[HikariCP-4.0.3.jar:na]
	at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:369) ~[HikariCP-4.0.3.jar:na]
	at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-4.0.3.jar:na]
	at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:476) [HikariCP-4.0.3.jar:na]
	at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) [HikariCP-4.0.3.jar:na]
	at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-4.0.3.jar:na]
	at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-4.0.3.jar:na]

org.h2.jdbc.JdbcSQLSyntaxErrorException: Schema “classpath:db/schema-h2.sql” not found [90079-200]

网上主要有三种处理方法:

  1. “initialization-mode:always” 在yml或者perproties中增加这个配置。(不加也没事)
  2. pom里面的数据库驱动要指定对应的version
  3. sql中不能有h2不支持的关键字,且关键字需要大写

这三种方法对我的情况无效。
经过排查发现原因是我的数据源配置问题:

#DataSource Config
initialization-mode=always
spring.datasource.hikari.driver-class-name=org.h2.Driver
spring.datasource.hikari.schema=classpath:db/schema-h2.sql
spring.datasource.hikari.data=classpath:db/data-h2.sql
spring.datasource.hikari.url=jdbc:h2:mem:test
spring.datasource.hikari.username=root
spring.datasource.hikari.password=test

我使用的springboot的版本是2.5.2,因为在spring.datasource后面增加了hikari,所以schema,data无法识别路径。如果不加,idea会包过时提示
Deprecated configuration property ‘spring.datasource.schema’ less…。
无奈只能先改成这个,来保证sql能够自动初始化,具体原因未知:
spring.datasource.schema=classpath:db/schema-h2.sql
spring.datasource.data=classpath:db/data-h2.sql