In my project I have entities for users and companies:
@Entity
@Table(name = \"users\")
public class UserDetails {
@Id
@GeneratedValue
@Column(n
I know this is old but it may help someone... I was trying to do the exact same thing - deleting from each main table to delete the referenced records first in the joined table and then delete the record from the main table. benzonico's post is valid but there is a more simple way to do this (without having to remove the records from the joined table yourself). The mapping at companies table needs to be changed to be a main table as well (don't use mappedBy):
@Entity
@Table(name = "companies")
public class CompanyDetails {
@Id
@GeneratedValue
@Column(name = "company_id")
private int id;
@Column(name = "name")
@NotEmpty
@Size(min = 1, max = 255)
private String name;
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "users_companies",
joinColumns = {@JoinColumn(name = "company_id")},
inverseJoinColumns = @JoinColumn(name = "user_id"))
private Set companyUsers = new HashSet();
}
That should do the trick. Now whenever you delete a company, Hibernate will first delete the records in users_companies and then it will delete the company itself. More info here: http://www.codereye.com/2009/06/hibernate-bi-directional-many-to-many.html