首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OneToMany关系不能保存在具有液态的春季

OneToMany关系不能保存在具有液态的春季
EN

Stack Overflow用户
提问于 2021-12-16 17:33:14
回答 1查看 731关注 0票数 1

我正试图在春季建立一个数据模型,这个模型以一对多的关系级联到3层以下,但我无法让它与清算脚本一起工作。

我使用spring引导与Kotlin和液化库与PostgreSQL数据库。

我到目前为止所做的:

  • 削减代码,只包含不起作用的部分(见下文)
  • 我尝试了@OneToMany和@JoinTable以及@JoinColumn,我也尝试了@ManyToMany,以排除@OneToMany
  • 的问题我运行了相同的代码(下面),没有清算库,让Hibernate/JPA从实际工作的模型
  • 中创建表,所以我从这些表中生成了清算脚本,但它们与我自己的完全相同(除了使用这些模型的关键names)
  • retrieving数据外(如果我直接通过SQL插入数据)

老实说,我不确定问题是在模型中,在配置中,还是在清算脚本中,所以我只发布所有这些。我缺少配置了吗?我配置的级联正确吗?我的模型定义/液化基脚本出错了吗?

我在保存父母方面的例外是:

代码语言:javascript
复制
Hibernate: insert into parent (name) values (?)
2021-12-15 23:29:16.797  WARN 14115 --- [    Test worker] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 23502
2021-12-15 23:29:16.798 ERROR 14115 --- [    Test worker] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: null value in column "id" of relation "parent" violates not-null constraint
  Detail: Failing row contains (null, Test 1).
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [id" of relation "parent]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
...
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
...
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "id" of relation "parent" violates not-null constraint
  Detail: Failing row contains (null, Test 2).

我试图运行的代码:

代码语言:javascript
复制
val parent = Parent(
    id = 0,
    name = "Test 2"
).apply {
    children = mutableSetOf(
        Child(
            id = 0,
            name = "Test 21",
            parent = this
        ).apply {
            grandchildren =
                mutableSetOf(
                    Grandchild(
                        id = 0,
                        name = "Test 211",
                        child = this
                    )
                )
        },
        Child(
            id = 0,
            name = "Test 22",
            parent = this
        )
    )
}

val saveParent: Parent = parentRepository.save(parent)

模型:

代码语言:javascript
复制
@Entity
class Parent(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0,
    var name: String,
    @OneToMany(mappedBy = "parent", cascade = [CascadeType.ALL])
    var children: MutableSet<Child> = mutableSetOf()
)
代码语言:javascript
复制
@Entity
class Child(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0,
    var name: String,
    @ManyToOne @JoinColumn(name = "child_id")
    var parent: Parent,
    @OneToMany(mappedBy = "child", cascade = [CascadeType.ALL])
    var grandchildren: MutableSet<Grandchild> = mutableSetOf()
)
代码语言:javascript
复制
@Entity
class Grandchild(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0,
    var name: String,
    @ManyToOne @JoinColumn(name = "child_id")
    var child: Child
)

application.yml

代码语言:javascript
复制
spring:
  datasource:
    platform: postgres
    url: jdbc:postgresql://localhost:5432/onetomany?ssl=false
    driver-class-name: org.postgresql.Driver
    initialization-mode: always
  jpa:
    database: postgresql
    database-platform: org.hibernate.dialect.PostgreSQLDialect
    generate-ddl: false
    hibernate:
      ddl-auto: none
  liquibase:
    enabled: true
    change-log: classpath:db/master.xml

清算脚本:

代码语言:javascript
复制
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.1.xsd">
  <changeSet author="bruce (generated)" id="data-1">
    <createTable tableName="parent">
      <column name="id" type="BIGINT">
        <constraints nullable="false" primaryKey="true" primaryKeyName="PK_PARENT"/>
      </column>
      <column name="name" type="VARCHAR(255)">
        <constraints nullable="false"/>
      </column>
    </createTable>
  </changeSet>
  <changeSet author="bruce (generated)" id="data-2">
    <createTable tableName="child">
      <column name="id" type="BIGINT">
        <constraints nullable="false" primaryKey="true" primaryKeyName="PK_CHILD"/>
      </column>
      <column name="name" type="VARCHAR(255)">
        <constraints nullable="false"/>
      </column>
      <column name="parent_id" type="BIGINT">
        <constraints nullable="false"/>
      </column>
    </createTable>
  </changeSet>
  <changeSet author="bruce (generated)" id="data-3">
    <createTable tableName="grandchild">
      <column name="id" type="BIGINT">
        <constraints nullable="false" primaryKey="true" primaryKeyName="PK_GRANDCHILD"/>
      </column>
      <column name="name" type="VARCHAR(255)">
        <constraints nullable="false"/>
      </column>
      <column name="child_id" type="BIGINT">
        <constraints nullable="false"/>
      </column>
    </createTable>
  </changeSet>
  <changeSet author="bruce (generated)" id="data-6">
    <addForeignKeyConstraint baseColumnNames="parent_id" baseTableName="child" constraintName="FK_CHILD_PARENT"
                             deferrable="false" initiallyDeferred="false" onDelete="RESTRICT" onUpdate="RESTRICT"
                             referencedColumnNames="id" referencedTableName="parent" validate="true"/>
  </changeSet>
  <changeSet author="bruce (generated)" id="data-8">
    <addForeignKeyConstraint baseColumnNames="child_id" baseTableName="grandchild" constraintName="FK_CHILD_GRANDCHILD"
                             deferrable="false" initiallyDeferred="false" onDelete="RESTRICT" onUpdate="RESTRICT"
                             referencedColumnNames="id" referencedTableName="child" validate="true"/>
  </changeSet>
</databaseChangeLog>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-16 18:46:18

@GeneratedValue(strategy = GenerationType.IDENTITY)通常通过在数据库中指定一个自动递增的默认值来工作,比如nextval('my_entity_sequence'::regclass)。插入时,DB将生成标识符。

在Postgres中,有serial/bigserial伪类型来指定一个自动增量列(这将在内部创建序列和列默认值),因此DDL可以例如如下所示:

create table my_entity ( id bigserial not null, primary key (id) )

https://www.postgresql.org/docs/current/datatype-numeric.html

在您的例子中,液化库忽略了所有ID列的类型/默认值(现在只是一个“父”-insert失败了,但是其他实体的插入也会失败)。

这是一个已知的清算基础问题:https://github.com/liquibase/liquibase/issues/1009 --围绕它工作的建议包括手动在变更集中指定autoIncrement="true"

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70383297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档