java - 映射到子表两次 - @OneToMany & @ManyToOne

标签 java hibernate jpa

我正在尝试对具有子实体集合 (childHistory) 以及指向最后添加的子实体 (currentChild) 的父实体建模

class Parent {
    //unidirectional
    @OneToOne(cascade = CascadeType.PERSIST, optional = false)
    @JoinColumn(name = "current_child_id")
    private Child currentChild;

    //bidirectional
    @OneToMany(mappedBy = "parent")
    private List<Child> childHistory;

    public Parent() {
        currentChild = new Child(this);
        childHistory = new ArrayList<>();
        childHistory.add(currentChild);
    }

    public void add() {
        currentChild = new Child(this);
        childHistory = new ArrayList<>();
        childHistory.add(currentChild);
    }
}

class Child {
    @ManyToOne(optional = false)
    @JoinColumn(name = "parent_id")
    private Parent parent;
    public Child(Parrent parent) {
        this.parent = parent;
    }
}

当前,当我尝试保存父级(并依靠级联来持久化子级)时,我得到了 transient 实体的异常。我无法事先保存 Parent,因为我在 Parent ctor 中初始化了所有内容。

警告(导致异常...):

WARN: HHH000437: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities. Unsaved transient entity: ([com.Parent#<null>]) Dependent entities: ([[com.Child#<null>]]) Non-nullable association(s): ([com.Child.entity])


WARN: HHH000437: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities. Unsaved transient entity: ([com.Child#<null>]) Dependent entities: ([[com.Parent#<null>]]) Non-nullable association(s): ([com.Parent.currentChild])

有没有一种方法可以正确建模并在 hibernate 时拥有 NOT NULL db 列。

编辑:要重现,请参阅此要点:https://gist.github.com/jlogar/2da2237640aa013f2cfbda33a4a5dc84

最佳答案

异常是指保存 transient 实体,这意味着您正在尝试保存与非托管实体有关系的实体,因为您的父级正在级联 onetoone 子级,那么问题出在 childHistory 上,因为这是双向的它会建立关系,因为级联 children 也是

@OneToMany(mappedBy = "parent",cascade=CascadeType.PERSIST)
private List<Child> childHistory;

关于java - 映射到子表两次 - @OneToMany & @ManyToOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45860992/

相关文章:

java - Android Spinner 获取所选项目

java - 不同队列的多个监听器 - Spring Rabbit

hibernate - 使用 ColdFusion ORM 缺乏变量的使用。实例范围?

java - 如何使用 JPA/Hibernate 将自定义数据结构映射到 bean 实体?

java - 如何从服务中定期捕获相机照片?

java - 类不是抽象的,并且不重写抽象方法 java 错误 TIcTacToe 游戏

java - 如何使用 hibernate 配置 Jaybird

与 "elements()"等效的 Hibernate Criteria API

java - 实现 Spring Data 存储库的自定义方法并通过 REST 公开它们

java - 坚持/提交在 Spring JPA JUnit 的测试环境中不起作用