TransWikia.com

Delete 1:1 parent form child entity without JPA mappings

Stack Overflow Asked by saran3h on August 11, 2020

I have a situation where I need to remove any associated parent when a child entity is removed and vice versa. But for “performance” reasons, the owner has not included any kind of JPA mappings in the entities. If i manually remove the parent first before deleting the child, it fails due to FK constraint and vice versa. Can anyone help?
Entities:

@Table(name = "child_node")
public class ChildNodeEntity {
    @Id
    private Long id;

    @Column(name = "case_id")
    private String caseId;

    @Column(name = "parent_id", updatable = false)
    private String parentId;
}

@Table(name = "parent_node")
public class ParentNodeEntity {
    @Id
    private Long id;

    @Column(name = "case_id")
    private String caseId;
}

Here in the child entity, parentId is kept as String (to avoid performance issues plus having the parent object has no use anywhere in the project).

Here’s the code for deletion of parent from child:

@Transactional
private void deleteBauCase(String caseId) {
    ChildNodeEntity child = service.getChildNodeEntityById(caseId);

    ParentNodeEntity parent = service.getParentNodeEntityById(caseId);
    parentNodeRepository.delete(parent);

    childNodeRepository.delete(child);
}

What should be done to delete both these entities? And the reverse case as well (delete child from parent).
I cannot use @OnetoOne mappings and cascade delete. Is there another way to execute this? The foreign key constraint is there on the database side. Please help as im only familiar in working with annotations.

One Answer

Solved it!

It turns out that the code is just fine (although a bit awful and non-standard).

The issue is with the foreign key constraint on DB. The on delete is set to no action by default. I only had to change it to set null.

Correct answer by saran3h on August 11, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP