Hibernate Bidirectional ManyToMany delete issue

让人想犯罪 __ 提交于 2019-12-01 06:47:17

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<UserDetails> 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

You have to have a CascadeType.REMOVE in your Cascade annotation of the property companyUsers of the entity CompanyDetails.

[Edit after comments]

Sorry i missed one thing in my answer is that it is a many to many. So the cascade delete won't work. Then the problem is that the responsible for the relationship is the UserDetails class. That is why it works on one way and not in the other one. Before deleting the company you may have to remove this company from the userCompanies set in each UserDetails of the companyUsers set.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!