OneMoreVladimir
OneMoreVladimir

Reputation: 1673

Hibernate questions

I started learning hibernate and I want to clarify some questions that cannot be cleared by simple googling. The questions are concerning interaction of deleteOrphan, cascade types and different association mapping types. Let me begin. Sincere thanks in advance.

@Entity
@Table(name = "t_member", schema = "church")
public class Member implements Serializable {
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
        @JoinTable(name = "t_event_members", joinColumns = {
                    @JoinColumn(name = "member_id")
                }, inverseJoinColumns = {
                    @JoinColumn(name = "event_id")
                })
    private Set<Event> events;
}

@Entity
@Table(name = "t_event", schema = "church")
public class Event implements Serializable {
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "events", 
            cascade = CascadeType.ALL)
        private Set<Member> members;
}
  1. The member is the owning side. During the active session I retrieve a member. If I remove an event from members collection and perform saveOrUpdate will the corresponding member be removed from the event?
  2. How does the "owning side" affects cascading in this case?
  3. What happens when we mix orphanDelete with CascadeType?

Upvotes: 0

Views: 128

Answers (1)

Steve Ebersole
Steve Ebersole

Reputation: 9443

1) Simply removing an event from the Member will have no effect in this case since you have not mapped orphan delete. The act of removing event from Member leaves that event an orphan, which is the basis of the term 'orphan delete'. And since you "retrieved the member during an active session", that member is "managed"; no need to call saveOrUpdate. The state of managed objects are tracked by Hibernate.

2) Most cascade types are valid on either side of an association (orphan-delete is the exception to this). Cascading says to cascade the operation just performed on the one thing to another. Owning or not describes which side Hibernate will use to drive the state of that association in the database. For illustration of this last point, here you have bi-directional many-to-many. Rows in the 't_event_members' table are represented twice in memory: once as element in Member.events and again as element in Event.members. Owning essentially defines which side to trust in cases where those 2 might be different.

3) orphan delete actually is cascade type to Hibernate. JPA defines it separately from cascade types (as annotation attribute) so we obviously support that as well.

BTW orphan delete and many-to-many are not compatible.

Upvotes: 1

Related Questions