【问题标题】:JPA Unidirectional mapping to insert list of Child entity along with Parent entity + Insert child separatelyJPA单向映射以插入子实体列表以及父实体+分别插入子实体
【发布时间】:2021-06-09 07:36:07
【问题描述】:

我的父子单向关系如下:

@Entity
@Table(name = "PARENT")
public class Parent {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private int parentId;

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

@Entity
@Table(name = "CHILD")
public class Child {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private int id;

    @Column(name = "PARENT_ID", insertable = false, updatable= false)
    private int parentId;

    //some other field
}

我创建了一个父实例,为其分配一个子列表并尝试将其持久化,它运行良好。

Parent p = new Parent();
List<Child> children = new ArrayList<Child>();
Child c = new Child();
children.add(c);
p.addChildren(children);
em.persit(p);
em.flush();

当我尝试通过子实体单独保存时,我看到插入查询正在尝试将 null 插入子表中的列 PARENT_ID 并导致

Child c = new Child();
c.setId(78987);
c.setParentId(12345);
em.persist(c);
em.flush();

独立于父表保存子实体时出现异常。我尝试插入的子实体与已经存在的父实体相关。

java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into (&quot;MY_SCHEMA&quot;.&quot;PARENT&quot;.&quot;PARENT_ID&quot;)_

将关系定义为单向后不能直接保存子实体吗?

【问题讨论】:

  • 这可能是因为 '@Column(name = "PARENT_ID", insertable = false, updatable= false)' , insertable = false

标签: spring hibernate jpa


【解决方案1】:

当您进行@Shekhar Khairnar 也提到的更改时,它将起作用。

向父级添加子级时效果很好,但在定义子级时不起作用。

You would do that when the responsibility of creating/updating the referenced column isn't in the current entity, but in another entity.

如果您要使用单向添加子对象,则应删除insertable = false 定义。

但是,这样的使用可能会导致数据不一致。你应该注意。

另外,定义child的时候不需要给id,因为这会根据你的model自动创建,不会取你给的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    相关资源
    最近更新 更多