0

I have a One to Many cardinality relationship like the following -

@Entity
@Table(name = "PARENT_TABLE")
public class Parent {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(name = "PARENT_ID", updatable = false, nullable = false, length = 16)
    @Type(type="uuid-binary")
    private UUID id;

    private String parentName;

    @OneToMany(fetch=FetchType.LAZY, mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name="PARENT_ID")
    private List<Child> children;

}

@Entity
@Table(name = "CHILD_TABLE")
public class Child {

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(name = "CHILD_ID", updatable = false, nullable = false, length = 16)
    @Type(type="uuid-binary")
    private UUID id;

    private String childName;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID")
    private Parent parent;

}

Now, I already have a parent with 2 children, I have an update call for parent which is updating some information in parent and adding one child in parent.

List<Child> existingChild = getFromDbByParent(parent);
existingChild.add(new Child());
hibernateTemplate.update(parent);
//hibernateTemplate.saveOrUpdate(parent);

The above code is failing, because for the 3rd child, hibernate is not creating ID while saving to DB. So, I am getting error

2019-12-19 13:02:04.589 DEBUG SqlExceptionHelper             io-12347-exec-1 could not execute batch [update CHILD_TABLE set CHILD_ID =null where PARENT_ID=?]

java.sql.BatchUpdateException: ORA-01407: cannot update ("DB"."CHILD_TABLE"."CHILD_ID") to NULL

Creation of parent along with new children is working fine, even with JPA Cascade annotations. What can be done here?

Note: It's a repo layer migration to hibernate project, so I am trying to avoid changes in logic which is Why to save new child in existing parent. I know, it's better to call save on child first.

Vivek Vardhan
  • 1,118
  • 3
  • 21
  • 44
  • 1
    That is not how you map a bidirectional association. Read the manual. https://docs.jboss.org/hibernate/orm/current/userguide/html_single/Hibernate_User_Guide.html#associations-one-to-many-bidirectional – JB Nizet Dec 19 '19 at 07:45
  • @JBNizet I have not used mappedBy, because I am using join column is not mandatory, because in my case join column name is different than what is the foreign key.. When join column is used, mapped by should not be given. – Vivek Vardhan Dec 19 '19 at 08:22
  • It is mandatory. You have two unrelated unidirectional associations there. The one side **must** be the inverse side. – JB Nizet Dec 19 '19 at 08:55
  • @JBNizet Here is the link of the answer: https://stackoverflow.com/a/11939045/1969412 Use of joinColumn, without using mappedBy – Vivek Vardhan Dec 19 '19 at 11:28

0 Answers0