我的类路径中有一个 import.sql 文件,其中包含一些 INSERT 语句。当使用 profile=devel 运行我的应用程序时,它的数据正在加载到 postgres 数据库中,到目前为止一切正常。
当使用测试配置文件 import.sql 执行测试时,也会触发导入,这会导致“找不到表”异常。不确定这里的原因是什么,但无论如何我都不想使用该数据进行测试。
我怎样才能阻止它?为测试配置文件设置 hibernate.ddl-auto=none 似乎不是解决方案,因为它也阻止了架构的生成。
最佳答案
据我所知,您无法配置它。只要您使用create-drop
或create
模式,Hibernate 就会自动调用import.sql
文件。 the documentation也提到了这一点与 Spring 无关:
In addition, a file named
import.sql
in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if theddl-auto
property is set tocreate
orcreate-drop
).
我的猜测是您仍然希望在测试场景中继续生成表格。在这种情况下,您可能希望通过在类路径中添加名为 schema.sql
和 data.sql
的文件来切换到 Spring boot 的数据源初始化。
此文件将在 Spring boot 启动时自动选取(仅适用于 Spring boot 2.0 中的嵌入式数据源),documentation 中也提到了这一点。 :
Spring Boot can automatically create the schema (DDL scripts) of your DataSource and initialize it (DML scripts). It loads SQL from the standard root classpath locations:
schema.sql
anddata.sql
, respectively.
现在,为了能够在测试阶段禁用加载数据,您可以使用配置文件。例如,对于 Spring boot 2.x,您可以使用以下属性禁用此功能:
spring.datasource.initialization-mode=never # Property for Spring boot 2.0
spring.datasource.initialize=false # Property for Spring boot 1.0
请注意,这会禁用架构创建和数据加载 SQL 文件。仅禁用 data.sql
文件是不可能的,但可以通过重命名 Spring boot 将查找的默认文件名来使用一个简单的技巧来实现:
spring.datasource.data=somethingelse.sql
如果您只在测试期间配置此属性,Spring boot 将查找名为 somethingelse.sql
的文件,而不会选择您的 data.sql
文件.当使用 dev 配置文件运行时,您丢弃此属性,Spring boot 将查找(并找到)data.sql
。
同时适用于 Spring boot 的 schema.sql
/data.sql
和 Hibernate 的 import.sql
的替代方法是使用 Maven配置文件并在运行测试时加载不同的类路径文件夹。但是,我不建议这样做,因为它会使在 IDE 中运行测试变得更加困难。
关于java - 如何防止在Spring Boot单元测试中执行import.sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41188207/