How to delete rows with forign key while deleting only the top level row in hibernate

Rohit Bajaj
Rohit Bajaj used Ask the Experts™
I am using hibernate for persistence.
Here are the two classes which i am using as entities :

@Entity(name = "workflow_template")

public class WorkflowTemplate {

 @GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

    @OneToMany(cascade = {CascadeType.ALL})
@JoinColumn(name = "workflow_id")
@OrderColumn(name = "task_idx")
 private List<TaskTemplate> taskTemplates;

@Entity(name = "task_template")

public class TaskTemplate {

    @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;

    @JoinColumn(name = "workflow_id", nullable = false)
private WorkflowTemplate workflowTemplate;

Open in new window

Now for deletion of the workFlowTemplate row i first need to delete the task template row and then delete the workflow_template row.
Is there a way where i could just specify delete the workflowTemplate row and it automatically deletes all the rest of such things which have a join in them.
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Distinguished Expert 2017
Unfamiliar with what you reference, you could use a trigger that cascades
The data organization will be the guide.

Deals with avoiding orphan records with foreign keys, I.e. If you deleting a parent reference, the cascading trigger will delete the child accounts before the parent row can be deleted.

Depending on the data an actual deletion might not be wise, using a deleted column, or similar to make a row as deleted while it would kit be generally displayed, the info will be retained in the event the deletion was in error.
mccarlIT Business Systems Analyst / Software Developer
Top Expert 2015
I'm not sure whether Hibernate has an inbuilt functionality, but depending on what database you are using, you may options there.

For instance, if you are using Oracle, when you create the foreign key relationship you can specify how it manages this scenario. One of these options is exactly what you want, it can delete any row that depends on the row being deleted.

Other DB's may/should have similar functionality.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial