spring 创建Postgres数据库,如果在运行Sping Boot 应用程序时它不存在

w8ntj3qf  于 2023-04-19  发布在  Spring
关注(0)|答案(5)|浏览(188)

我正在使用PostgreSQLspring-boot-2.0.1,希望我的应用程序在数据库不存在时创建数据库。我在application.properties中有以下选项

spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL94Dialect

spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
spring.datasource.username=postgres
spring.datasource.password=123

上面的我得到了错误:

Caused by: org.postgresql.util.PSQLException: FATAL: database "mydb" does not exist

知道我错过了什么吗?

8yparm6h

8yparm6h1#

由于所有Postgres安装都带有一个默认数据库,因此从技术上讲,应该可以在一开始(当应用程序启动时)连接到它,然后调用
CREATE DATABASE
这是您可以在spring初始化之前,但在读取属性之后,例如在Environment Post Processor中,通过编程方式完成的事情
之所以需要这么早的调用,是因为一方面您可能希望利用spring Boot 读取的属性,但到spring boot beans开始获取处于“操作”状态的新创建的数据库时。
所以,从技术上讲是可能的。但是,我看不到这种情况的真实的用例。如果是测试,那么你可以完美地使用默认的Postgres数据库,这在问题的开头就提到了。
如果是用于生产环境-通常DBA不会允许这样做,因为为了能够运行CREATE DATABASE语句,连接到Postgres(在本例中为spring Boot 应用程序)的用户应该具有非常“强”的 createdb 特权,DBA不会真正想要共享这些特权。

628mspwn

628mspwn2#

如果spring boot不存在数据库,您可以创建数据库。至少在MySQL中,我们可以:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb?createDatabaseIfNotExist=true

所以PostgreSQL应该是一样的:

spring.datasource.url= jdbc:postgresql://localhost:5432/mydb?createDatabaseIfNotExist=true

这不适用于PostgreSQL。

cwxwcias

cwxwcias3#

**Sping Boot **

Postgres不支持createDatabaseIfNotExist=true,所以你可以尝试类似的方法,它为我工作,见Screenshot

@SpringBootApplication
public class SpringSecurityJwtApplication{

    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger(SpringSecurityJwtApplication.class);
        Connection connection = null;
        Statement statement = null;
        try {
            logger.debug("Creating database if not exist...");
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/", "postgres", "postgres");
            statement = connection.createStatement();
            statement.executeQuery("SELECT count(*) FROM pg_database WHERE datname = 'database_name'");
            ResultSet resultSet = statement.getResultSet();
            resultSet.next();
            int count = resultSet.getInt(1);

            if (count <= 0) {
                statement.executeUpdate("CREATE DATABASE database_name");
                logger.debug("Database created.");
            } else {
                logger.debug("Database already exist.");
            }
        } catch (SQLException e) {
            logger.error(e.toString());
        } finally {
            try {
                if (statement != null) {
                    statement.close();
                    logger.debug("Closed Statement.");
                }
                if (connection != null) {
                    logger.debug("Closed Connection.");
                    connection.close();
                }
            } catch (SQLException e) {
                logger.error(e.toString());
            }
        }
        SpringApplication.run(SpringSecurityJwtApplication.class, args);
    }
}
pn9klfpd

pn9klfpd4#

简答:

它不能像我们在MySQL中所做的那样完成,您需要在Spring Configuration之外找到一种自己完成的方法

hgncfbus

hgncfbus5#

一个解决方案是添加创建数据库的脚本......即使,你在postgres中没有“if not exist”。下面是我如何用docker文件解决这个问题的,但我想你可以在postgres中做一个sql脚本。我把这个放在www.example.com中initdb.sh......

set -e
export PGPASSWORD=$POSTGRES_PASSWORD;
psql -v ON_ERROR_STOP=1 --username "root" --dbname "mydb" <<-EOSQL
  SELECT 'CREATE DATABASE mydb' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')\gexec
  GRANT ALL PRIVILEGES ON DATABASE mydb TO root;
  \connect mydb root
EOSQL

相关问题