Tuesday, April 28, 2009

Cascade

We may get FK constraint exception when we try to delete the parent record (e.g., Player table). We can define database level cascade such as "on delete cascade|set null".


create table player_stats (
`id` integer unsigned not null auto_increment,
`player_id` integer unsigned not null,
primary key (`id`),
foreign key (`player_id`) references player (`id`) on delete cascade
)
engine = InnoDB;

Note that it is uni-directional. Only works for parent -> child cascade.

With Hibernate cascade, we don't need to define this on DDL. And the cascade is more flexible - bi-directional. We can cascade change from any side following the association link (one-to-many, many-to-one, many-to-many etc). It handles cascade on higher level, i.e., entity to entity. On example is tbl_apGroup, tbl_apGroup_ap, tbl_ap. The database cascade would be defined on FK tbl_apGroup_ap referencing to tbl_apGroup. But Hibernate cascade is from domain object ApGroup to Ap.

No comments: