persistence@glassfish.java.net

Re: cascading removals only when last foreign key is removed

From: Marina Vatkina <Marina.Vatkina_at_Sun.COM>
Date: Tue, 24 Apr 2007 19:27:29 -0700

Hi John,

I think that you are facing the "orphan-delete" problem that has been left
behind the 1st version of the spec (together with several other features that
didn't have enough time to be sorted out). For now your only portable solution
is to check the collection size manually (no cascade flags) and when it has only
one player left, remove the team yourself.

Now the cascade flags do not need to be on the owning side. More than that - in
most cases they'll be located on the inverse side (adding a team, will add all
its players and vice versa).

HTH,
-marina

John O'Conner wrote:
> I have two entities:
>
> Player
> Team
>
>
> Player is in a M:1 bidirectional relationship with Team. Player is the
> owner.
>
> Player's team property has the @ManyToOne(cascade=CascadeType.ALL)
> annotation.
>
> Now when I remove a single Player, the Team is also removed. Obviously
> that's wrong when other players belong to that team, and I guess I need
> to remove the cascade attribute. However, I would like the associated
> team removed when the last player is removed. Is there a slick way to do
> this without performing my checks to see whether the team_id is still in
> PLAYER?
>
> The tables look like this:
>
> PLAYER
> id, name, jerseynumber, team_id
>
> TEAM
> id, name, league
>
>
> Regards,
> John O'Conner