JPA hibernate外键未在实体

时间:2018-01-01 07:55:53

标签: hibernate jpa

我正在使用CASCADE.PERSIST

执行父子节省
@Entity
@Table(name = "parent")
public class Parent extends AbstractAuditingEntity{

    @OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.PERSIST)
    @JoinColumn(name = "parent_id",nullable = false)
    private List<Child> children;

}


@Entity
@Table(name = "child")
public class Child extends AbstractAuditingEntity{

    @Column(name = "parent_id", insertable=false, updatable=false)
    private Long parentId;

}

当我保存父母时,孩子也会与外键一起保存。

parent = parentRepository.save(parent);

但是从存储库返回的实体没有在子节点中设置foriegn键。

child.getParentId()为空。

无论如何我能完成它吗?

尝试在子项中设置父项,但存在同样的问题

@Entity
@Table(name = "child")
public class Child extends AbstractAuditingEntity{

    @ManyToOne
    @JoinColumn(name="parent_id",nullable = false,insertable=false,updatable=false)
    private Queue queue;
}

虽然这不是一个关键问题(我可以从父母手动设置) - 只是想确定我做得对。

2 个答案:

答案 0 :(得分:0)

保存没有任何魔力。这意味着如果您未设置parentId,则此字段为空。你必须自己设置它。

当您使用find或查询读取数据时,该字段将由JPA设置。

答案 1 :(得分:0)

正如JB Nizet所指出的,双向映射是不正确的。

这已根据以下链接进行了更正,并且工作正常

https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/