首页 > 解决方案 > Spring boot 和 postgresql:执行 import.sql 文件时出现奇怪的错误

问题描述

我有一个 Spring Boot 应用程序,我使用 Spring Data JPA 和 PostgreSQL 作为数据库。我让 hibernate 创建模式并且运行良好,但是当我尝试使用 import.sql 文件填充数据库时,会出现错误。这是错误:

CommandAcceptanceException: Error executing DDL "insert into users(user_id, username, email, password, created_at)" via JDBC Statement
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at end of input.

这是我的 import.sql 文件:

insert into users(user_id, username, email, password, created_at)
values(1, 'alex', 'alex@email.com', 'pword', current_timestamp);

这是我的 application.properties 文件:

spring.datasource.url=jdbc:postgresql://localhost:5432/website
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQL95Dialect
spring.datasource.username=alexander
spring.datasource.password=
spring.jpa.show-sql=true
# drop n create table again, good for testing, comment this in production
spring.jpa.hibernate.ddl-auto=create-drop
# spring.sql.init.data-locations= classpath:/data.sql
# spring.datasource.initialization-mode=always
# spring.sql.init.mode=always
# spring.jpa.defer-datasource-initialization=true

application.properties 中被注释掉的部分是我在我尝试过的其他线程中发现的东西,但结果没有变化。

每个表都被完美地创建,如果我复制 import.sql 的内容并通过终端或 pgadmin 将其插入到 PostgreSQL 中,那么它可以完美地工作并且用户被插入时出现 0 个问题。所以我真的不明白这个“输入结束时的语法错误”是什么。可能。

PS。单词 current_timestamp 也不是问题,如果我将它与例如 ('2020-05-06 08:30') 交换,我仍然会得到完全相同的错误。

标签: springpostgresqlspring-boothibernatespring-data-jpa

解决方案


对于这个问题,你有比将 SQL 插入移动到一行更好的解决方案。只需在 application.properties 中添加 jpa 属性,它允许您将 SQL 语句放在多行中:

jpa:
  properties:
    hibernate.hbm2ddl.import_files_sql_extractor: org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor

在两行(或多行)中包含 SQL 插入语句可以提高可读性


推荐阅读