Подтвердить что ты не робот

Spring Загрузка с Hibernate, генерирующая ошибки ограничения при запуске с базой данных H2

Я использую spring-boot и настроил базу данных H2 следующим образом (в application.properties).

spring.datasource.url=jdbc:h2:mem:AZ;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

В логах я вижу следующие ошибки:

o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
        name: default
        ...]
org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.5.Final}
org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: alter table key_request drop constraint FK_53shrbc21c25inskpp1yoxxss if exists
org.hibernate.tool.hbm2ddl.SchemaExport  : Table "KEY_REQUEST" not found; SQL statement:
    alter table key_request drop constraint FK_53shrbc21c25inskpp1yoxxss if exists [42102-178]

Несмотря на то, что hibernate сообщает об этом как об ошибках, я могу войти в консоль H2 и увидеть ограничения, и они кажутся просто нормальными.

SELECT TABLE_NAME, INDEX_NAME, COLUMN_NAME, INDEX_TYPE_NAME FROM information_schema.indexes WHERE TABLE_NAME='KEY_REQUEST';
TABLE_NAME    INDEX_NAME                            COLUMN_NAME  INDEX_TYPE_NAME  
KEY_REQUEST   PRIMARY_KEY_F                         REQUEST_ID   PRIMARY KEY
KEY_REQUEST   FK_53SHRBC21C25INSKPP1YOXXSS_INDEX_F  USER_ID      INDEX

Если действительно похоже, что hibernate пытается удалить эти ограничения, прежде чем он фактически создаст базу данных (то есть какая-то ошибка в hibernate). Есть ли способ избежать этих ошибок, засоряющих журналы, или они указывают на реальный сбой где-то?

ОБНОВЛЕНИЕ 1

Попытка заставить приложение выполнять обновления только с помощью этого параметра:

spring.jpa.hibernate.ddl-auto=update

Приводит к следующим ошибкам (все остальные ошибки исчезают):

org.hibernate.tool.hbm2ddl.SchemaUpdate  : HHH000388: Unsuccessful: alter table lti_result add constraint FK_1cnh9amy5br8owkmafsrth3as foreign key (result_id) references lti_link
org.hibernate.tool.hbm2ddl.SchemaUpdate  : Constraint "FK_1CNH9AMY5BR8OWKMAFSRTH3AS" already exists; SQL statement: 
    alter table lti_result add constraint FK_1cnh9amy5br8owkmafsrth3as foreign key (result_id) references lti_link [90045-178]

ПРИМЕЧАНИЕ: источник здесь: https://github.com/azeckoski/lti_starter

Конкретно конфиг: https://github.com/azeckoski/lti_starter/blob/master/src/main/resources/application.properties

и модель:https://github.com/azeckoski/lti_starter/tree/master/src/main/java/ltistarter/model

4b9b3361

Ответ 1

Поскольку вы используете базу данных в памяти, Hibernate не найдет ни одной таблицы при выполнении:

hibernate.hbm2ddl.auto=create-drop

Это потому, что порядок заявлений:

  • снять ограничения (FK)
  • бросить столы
  • создать таблицы
  • создать ограничения (fk)

    Query:{[alter table tableIdentifier drop constraint FK_202gbutq8qbxk0chvcpjsv6vn][]} 
    ERROR [main]: o.h.t.h.SchemaExport - HHH000389: Unsuccessful: alter table tableIdentifier drop constraint FK_202gbutq8qbxk0chvcpjsv6vn
    ERROR [main]: o.h.t.h.SchemaExport - user lacks privilege or object not found: PUBLIC.TABLEIDENTIFIER
    Query:{[drop table sequenceIdentifier if exists][]} 
    Query:{[drop table tableIdentifier if exists][]} 
    Query:{[create table sequenceIdentifier (id bigint not null, primary key (id))][]} 
    Query:{[create table tableIdentifier (id bigint not null, sequenceIdentifier_id bigint, primary key (id))][]} 
    Query:{[alter table tableIdentifier add constraint FK_202gbutq8qbxk0chvcpjsv6vn foreign key (sequenceIdentifier_id) references sequenceIdentifier][]} 
    Query:{[create sequence hibernate_sequence start with 1 increment by 1][]} 
    

Вы можете исправить это, изменив hibernate.hbm2ddl.auto для обновления:

hibernate.hbm2ddl.auto=update

Ответ 2

Попробуйте create-only:

spring.jpa.properties.hibernate.hbm2ddl.auto=create-only

Он был добавлен в Hibernate, по крайней мере, начиная с 5.2 (возможно, даже раньше), и я не нашел нужной документации, но там упоминалось Руководство пользователя: 23.15. Автоматическая генерация схемы

Также, если вы видите в журналах:

WARN  SessionFactoryOptionsBuilder:394 - Unrecognized hbm2ddl_auto value : create-only.  Supported values include 'create', 'create-drop', 'update', 'none' and 'validate'.  Ignoring

Это может быть ложная тревога, и на самом деле это работает

Ответ 3

спасибо, эта работа для меня.

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.username=postgres
spring.datasource.password=postgres
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL9Dialect
# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto=create
logging.level.org.hibernate.SQL= DEBUG
hibernate.hbm2ddl.auto=update

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
# Enable response compression
server.compression.enabled=true
# The comma-separated list of mime types that should be compressed
server.compression.mime-types=text/html,text/xml,text/plain,text/css,text/javascript,application/javascript,application/json
# Compress the response only if the response size is at least 1KB
server.compression.min-response-size=1024
server.http2.enabled=true
# Maximum time the response should be cached (in seconds)
spring.resources.cache.cachecontrol.max-age=120
# The cache must re-validate stale resources with the server. Any expired resources must not be used without re-validating.
spring.resources.cache.cachecontrol.must-revalidate=true
#https://www.callicoder.com/configuring-spring-boot-application/
server.port=8080