0

I have parent-children unidirectional relation as follows:

@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
}

I create an instance of the parent, assign a list of children to it and try to persist it and it works well.

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();

When I try to save via Child entity separately, I see that the insert query is trying to insert null to column PARENT_ID in Child Table and results in

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

Exception while saving Child Entity independent of Parent table. The Child entity that Im trying to insert is related to the Parent entity that exists already.

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

Is it not possible to save Child entity directly after defining the relation as Unidirectional?

Alagammal P
  • 829
  • 5
  • 19
  • 43

1 Answers1

0

It will work when you make the change that @Shekhar Khairnar also mentioned.

It works well when you add a child to the parent but does not work when defining a child.

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

If you are going to use unidirectional and add a child object, you should remove the insertable = false definition.

However, such usage may result in data inconsistency. You should pay attention.

In addition, you do not need to give an id when defining a child, because this will be created automatically according to your model and will not take the value you give.

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29