spring-data-jpa Hibernate一对一关系需要从父域对象传递子值

xn1cxnb4  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(146)

我已经用Hibernate和Kotlin创建了下面的OneToOne关系。但是,当我初始化Parent()时,它要求我将child值设置为Parent(child=null),这是不期望的。只有初始化子项时才要求父项为Child(parent=Parent(...),如果我同时将父项添加到子项,又将子项添加到父项,这将创建一个无限循环。如何避免这种情况?

@Entity
    class Parent(
        @Id
        @Column(nullable = false, updatable = false, columnDefinition = "uuid")
        val id: UUID = UUID.randomUUID(),
        @OneToOne(cascade = [CascadeType.ALL], mappedBy = "parent")
        @JsonIgnore
        @JoinColumn(name = "child_id", referencedColumnName = "id")
        val child: Child?
    )
    @Entity
    class Subscriber(
        @Id
        @Column(nullable = false, updatable = false, columnDefinition = "uuid")
        val id: UUID = UUID.randomUUID(),
        @OneToOne(cascade = [CascadeType.ALL], optional = false)
        @JoinColumn(name = "id", columnDefinition = "uuid")
        @MapsId
        val parent: Parent
    )
wh6knrhe

wh6knrhe1#

由于父项和子项是一对一Map,您希望使用@MapsId,以便不在子表中创建另一个额外PK现在子对象将使用具有自己PK parent_id
对于父级

@Entity
public class Parent {
    @Id
    @Column(nullable = false, updatable = false, columnDefinition = "uuid")
    private UUID id = UUID.randomUUID();

    public UUID getId() {
        return id;
    }

    public Parent setId(UUID id) {
        this.id = id;
        return this;
    }
}

子项

@Entity
public class Child {
    @Id
    @Column(nullable = false, updatable = false, columnDefinition = "uuid")
    private UUID id = UUID.randomUUID();

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private Parent parent;

    public UUID getId() {
        return id;
    }

    public Child setId(UUID id) {
        this.id = id;
        return this;
    }

    public Parent getParent() {
        return parent;
    }

    public Child setParent(Parent parent) {
        this.parent = parent;
        return this;
    }
}

查看下面的屏幕截图,了解表在数据库中的外观。x1c 0d1x

相关问题