首页 > 解决方案 > 在 Spring 应用程序的类路径中找不到 Schema.sql

问题描述

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必须在类路径上才能读取属性(这会被读取并导致找不到资源的错误)。

我是在搞乱类路径还是我错过了一些可以指定每次应用程序在开发环境中运行时如何初始化我的数据库的属性?

标签: javaspringspring-data

解决方案


作为一种解决方案,我检查了我的配置文件 ( 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);
        }

推荐阅读