lsaffie
lsaffie

Reputation: 1814

Deleting Objects in Many to Many association with Hibernate and Java

I've been searching for days but can't seem to find the answer.

Given this many to many (employee/meeting)

@Entity
@Table(name="EMPLOYEE")
public class Employee {

    @Id
    @Column(name="EMPLOYEE_ID")
    @GeneratedValue
    private Long employeeId;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name="EMPLOYEE_MEETING",
                joinColumns={@JoinColumn(name="EMPLOYEE_ID")},
                inverseJoinColumns={@JoinColumn(name="MEETING_ID")})
    private Set<Meeting> meetings = new HashSet<Meeting>();
}

@Entity
@Table(name="MEETING")
public class Meeting {

    @Id
    @Column(name="MEETING_ID")
    @GeneratedValue
    private Long meetingId;

    @ManyToMany(mappedBy="meetings")
    private Set<Employee> employees = new HashSet<Employee>();
}

I can add employees to a meeting and it shows up in the employee_meeting table.

When I do get a meeting object and delete it, it's also gone from the join table but remains in the employee set... Is this the expected behaviour?

Here's how I would remove a meeting object

session.delete(meeting);
transaction.commit();

At this point it's gone from the table.

Thanks!

Upvotes: 4

Views: 9394

Answers (1)

kandarp
kandarp

Reputation: 5047

Yes this is correct behaviour. If you have many-to-many relationship, then you need to delete it manually. Please refer this link for hibernate collection mapping strategy

Upvotes: 1

Related Questions