【问题标题】:Spring Boot & Hibernate fail to autocreate table when an Entity is self refernced当实体自引用时,Spring Boot 和 Hibernate 无法自动创建表
【发布时间】:2022-01-24 01:22:51
【问题描述】:

我正在使用 spring bootHibernate ,并且我有以下实体

@Entity
public class SystemicLevel {

@Id
private Long id;

@Column
private String name;

@Column
private String detail;

@OneToOne
@JoinColumn(name="previous_Level")
private SystemicLevel previousSystemicLevel;

}

application.properties 文件中,我将 spring.jpa.hibernate.ddl-auto 属性设置为 "create" 所以当我运行应用程序时,我得到了这个错误:

org.hibernate.tool.schema.spi.CommandAcceptanceException: 错误 执行 DDL "alter table systems_level 添加约束 FKehejw8ac9k3req7redt7ef4uv 外键(previous_level)引用 system_level (id)" 通过 JDBC 语句

我认为当 Hibernate 尝试创建 systemic_level 表时,它会尝试使用 previous_level 列自行引用该表,但该表尚未创建,因此它会抛出例外。

我想知道是否存在此问题的解决方案。

【问题讨论】:

    标签: spring-boot hibernate jpa spring-data


    【解决方案1】:

    使用

    @OneToOne
    @JoinColumn(name="previous_Level", nullable = true)
    private SystemicLevel previousSystemicLevel;
    

    更新属性

    spring.jpa.hibernate.ddl-auto=update
    

    如果仍然存在问题,请使用以下属性跟踪从 jdbc 执行的查询,然后您可以轻松跟踪 sql 执行查询日志并基于该更改。

    logging.level.org.hibernate.SQL= DEBUG
    spring.jpa.properties.hibernate.format_sql=true
    

    【讨论】:

    • 感谢您的回答,效果很好,但我需要使用spring.jpa.hibernate.ddl-auto=create 进行测试
    • 你在日志中看到过休眠尝试执行的查询吗?
    • 无缘无故将spring.jpa.hibernate.ddl-auto 更改为update 就像您说的那样有效,当我将其更改为create 时它仍然有效,不知道为什么,但感谢您的帮助跨度>
    • 表已创建,但当休眠尝试执行此查询时抛出以下异常:alter table systemic_level drop constraint FKehejw8ac9k3req7redt7ef4uvorg.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL " alter table systemic_level drop constraint FKehejw8ac9k3req7redt7ef4uv" via JDBC Statement... ... Caused by: org.postgresql.util.PSQLException: ERROR: constraint "fkehejw8ac9k3req7redt7ef4uv" of relation "systemic_level" does not exist
    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2021-10-31
    • 2019-06-30
    • 2017-07-31
    • 2019-01-21
    相关资源
    最近更新 更多