模式.sql在 Spring 应用程序的类路径上找不到



我的资源文件夹中有一个schema.sql文件以及用于应用程序设置的application-dev.yml,它如下所示:

-- Drop the tables
DROP TABLE IF EXISTS customers;
-- Create tables
CREATE TABLE customers (
id SERIAL,
first_name VARCHAR(255),
last_name VARCHAR(255)
);
-- Populate data
INSERT INTO customers(first_name, last_name) VALUES ('Jane', 'Doe');
INSERT INTO customers(first_name, last_name) VALUES ('Josh', 'Gruber');
INSERT INTO customers(first_name, last_name) VALUES ('Hans', 'Gruber');
INSERT INTO customers(first_name, last_name) VALUES ('John', 'Doe');

但是在应用程序启动时它不会被挖掘出来,因为当我尝试在程序中查询它时,我收到一个错误,说"客户"不存在。我尝试手动设置属性spring.datasource.schema: 'schema.sql'但是出现错误,说[schema.sql] resource doesn't exist on the classpath.我知道它确实如此,因为application-dev.yml必须是类路径上的属性才能被读取(这会被读取并导致找不到资源的错误)。

我是否弄乱了类路径,或者我是否缺少一些可以指定每次应用程序在开发环境中运行时如何初始化数据库的属性?

作为解决方法,我检查了我的配置文件 (spring.profiles.active) 是否包含dev如果包含,则执行资源schema.sql。令人惊讶的是,ResourceDatabasePopulator在运行时发现了这一点,没有错误。以下是我用作解决方案的代码:

@Autowired
Environment env;
// If the environment is dev, then run schema.sql to reinitialize the schema and repopulate test data
if(env.getActiveProfiles()[0].equalsIgnoreCase("dev")) {
Resource resource = new ClassPathResource("schema.sql");
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(resource);
databasePopulator.execute(dataSource);
}

最新更新