在Spring Boot中创建数据库表后运行自定义脚本 [英] Run custom script after database tables are created in Spring Boot
问题描述
我在我的项目中使用带有gradle的Spring Boot, ─主$ b $│├──java
│└──资源
│└──import.sql
├──脚本
│└──custom_script.sql
└──test
├──java
│├──持久化
││└──UserRepositoryTest.java
│└──TestConfiguration.java
└──资源
└──import.sql
位于 custom_script.sql
我有一些我的应用程序需要的sql脚本,例如在插入之前触发等等。可以配置应用程序,例如使用应用程序属性文件,使用hibernate或其他方式来加载该脚本,并在创建表之后创建我的触发器?
表我已经定义为JPA实体。因此,我预期的步骤顺序是:
$ b $ ol <
resources / import.sql加载插入脚本
为了测试目的,我试着创建 TestConfiguration .java
接口在这里我使用 @Sql
类似的附加内容:
@Sql(src / scripts / custom_script.sql)
public interface TestConfiguration {
}
接下来我想用这个接口进行测试,需要这样的脚本:
@Transactional
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserRepositoryTest实现TestConfiguration {
}
问题在于:
- 我的解决方案没有工作
- 它仅包含测试用例,而不是应用程序正常启动时的情况
您能帮我解决吗?谢谢。
>然而,您可以尝试以下操作。 c $ c>在您的UserRepositoryTest类上添加Annotation,并将路径更改为: 如果你想在其他测试中使用它,请创建一个抽象测试类和所需的注释。 如果您需要真正的数据库迁移,请查看Flyway: https://flywaydb.org/ I am using Spring Boot with gradle in my project with following project structure: in Tables I have defined as JPA Entities. So my expected steps order is: For test purpose I tried create and next I wanted to use this interface for tests which requires this script like that: Problem is that : Can you help me with that please? Thanks. However you could try the following.
Add the script to your classpath by putting your scripts folder under src/test/resources Then set the If you want to use it on other Tests please create an abstract testclass with the needed annotations. If you need real Database migration have a look at Flyway: https://flywaydb.org/ 这篇关于在Spring Boot中创建数据库表后运行自定义脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
通过将脚本文件夹放在src / test / resources下将脚本添加到classpath中。然后将 @SQL $>设置为
@SQL(classpath:scripts / custom_script.sql)
$ b
src/
├── main
│ ├── java
│ └── resources
│ └── import.sql
├── scripts
│ └── custom_script.sql
└── test
├── java
│ ├── persistent
│ │ └── UserRepositoryTest.java
│ └── TestConfiguration.java
└── resources
└── import.sql
custom_script.sql
I have some sql scripts which my application requires, e.g. triggers before inserts and so on. Is possible to configure application, for example with application properties file, with hibernate, or some another way to load that script and create my triggers after tables will be created?
resources/import.sql
TestConfiguration.java
interface where I use @Sql
anotation like that:@Sql("src/scripts/custom_script.sql")
public interface TestConfiguration {
}
@Transactional
@SpringBootTest
@RunWith(SpringRunner.class)
public class UserRepositoryTest implements TestConfiguration {
}
@SQL
only works on Tests:@SQL
Annotation on your UserRepositoryTest Class and change the path to:@SQL(classpath:scripts/custom_script.sql)