permaculture playing cards*
The moose likes Object Relational Mapping and the fly likes update child foreign column when parent is deleted Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "update child foreign column when parent is deleted" Watch "update child foreign column when parent is deleted" New topic
Author

update child foreign column when parent is deleted

ankur jadiya
Greenhorn

Joined: Feb 15, 2013
Posts: 4
my requirement is when i delete the parent ,child should not be deleted but instead of deleting child,one of the child column department_ID which is foreign key must be update with some value , say one department(Parent Table) contains many employee and employee(child Table) table have Department_ID as a foreign key column .The problem i m facing when i delete the parent table nothing is reflected on child cause i have make updatable=false if i will make it true then on deleting parent ,child column is set to null or if i update the parent then also child Department_Id column set to null which is violating the requirement so that's why i make it false .I don't want child to be update when the parent make any changes only changes should reflected on delete operation ,only on one column. Please help me what should i do? thanks

This is my Praent Table(Department code)


This is child table Employee code
T Mishra
Ranch Hand

Joined: Apr 04, 2006
Posts: 108

I am not sure if this will work but you can try the following approach and let us know.
when i delete the parent ,child should not be deleted

@OneToMany(fetch = FetchType.EAGER, orphanRemoval=false)

use of updatable=false looks correct to me
i delete the parent ....one of the child column department_ID which is foreign key must be update with some value

This seems to be specific to Delete Event. I assume when relationship is deleted, in the entity Department, Collection<Employee> employeeList is set to null

You may define an even listener for delete action here. More description about event here
Implement PreCollectionRemoveEventListener and add it to your Configuration

In the listener method onPreRemoveCollection(PreCollectionRemoveEvent event)

1. create PreCollectionRemoveEvent pass the collection employeeList in constructor,
2. for each Employee in Collection<Employee> employeeList
set DEPARTMENT_ID = <default_value>
save employee

If PreCollectionRemoveEvent doesn't work, you may try PreCollectionUpdateEvent


Thanks,
Tushar (SCJP 1.5)
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: update child foreign column when parent is deleted