springboot启动没有执行data.sql文件

clipboard.png

clipboard.png

数据库能成功链接和创建数据库
我需要执行data.sql来初始化数据测试
我看来一下文档,springboot会自动扫描classes下面有没有这个文件,也可以在配置里面自动配置。我自己配置指定文件,也没有生效。不知道扫描原因。我知道ddl-auto不能和schema.sql一起使用。

阅读 10.9k
3 个回答

我解决了问题,以下有几个解决方案。我发现我读文档没有那么仔细。附上文档链接springdoc

  1. ddl-auto改成create或者create-drop,将data.sql改成import.sql,但是会在执行insert的时候出现一些问题。
  2. datasource下initialization-mode设置为always但是每次启动都会导入data.sql
  3. 好了两个都有问题,那么就把它们合起来就是第三个解决方案。

最后initialization-mode没有读懂他的意思,当然不是英文没读懂,而是没有看懂在初始化的作用。我看的有点懵,For instance, if you want to always initialize the DataSource regardless of its type特别是这句话,希望有大佬指点以下。

1 springboot 进行数据库初始化的类org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer

生成用户创建数据库DDL脚本的方法 getScripts
如果应用配置了spring.datasource.schema那么使用应用配置
否则自动查找 classpath*:schema-${plateform}.sql 和 classpath*:schema.sql
既然spring使用 classpath* 那么使用classpath* 作为prefix应该就没有问题了.

2 spring的资源解析大部分都是通过PathMatchingResourcePatternResolver 进行解析
可以看一下spring的resource加载器 PathMatchingResourcePatternResolver
大概意思是如果不是classpath*开头的资源,那么默认使用 classLoader去加载.
所以可以删除classpath:前缀应该也可以解决问题

3当然如果特殊情况,比如脚本放到了某个jar包的classpath下面,那么就需要考虑用classpath*:**/data.sql 这种形式了

4 注意的是下面这种格式也会导致PathMatchingResourcePatternResolver 解析不到
classpath*:data.sql,因为对于没有通配符的路径,PathMatchingResourcePatternResolver 也会使用classLoader去加载

5 至于ddl-auto 这个属性,如果是使用内嵌数据库的话 默认是create-drop 这个属性和ddl dml的关系没搞明白,懂的大神可以答复一下.

DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Defaults to "create-drop" when using an embedded database and no schema manager was detected. Otherwise, defaults to "none".

6 补充一下 原来到你说的是data.sql不会执行,原因在这里没有schema的话 data就不会执行,所以取巧的办法,可以创建一个空的schema文件试试
这个是执行data脚本的逻辑,先执行schema,如果schema执行没有问题执行数据脚本dml
image.png
schema加载并执行
image.png

spring: 
  datasource:
    data: classpath:data.sql

试一试可以吗??

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题