在我的项目中,我有用户和公司的实体:
@Entity
@Table(name = "users")
public class UserDetails {
@Id
@GeneratedValue
@Column(name = "user_id")
private int id;
@Column(name = "first_name")
@NotEmpty
@Size(min = 2, max = 20)
private String firstName;
@ManyToMany(cascade = CascadeType.REFRESH)
@JoinTable(name = "users_companies",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "company_id"))
private Set<CompanyDetails> userCompanies = new HashSet();
//getters and setters of course...
}
@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(mappedBy = "userCompanies")
private Set<UserDetails> companyUsers = new HashSet();
}
我将用户分配给公司,然后尝试删除。当我删除用户时,一切正常 - 用户已删除,“users_companies”表中的记录也已删除,公司仍保留(根据需要)。但是,当我尝试删除一家公司时,我的堆栈跟踪具有以下根本原因:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`d_torianik/users_companies`, CONSTRAINT `FK447D806437A764EB` FOREIGN KEY (`company_id`) REFERENCES `companies` (`company_id`))
你能帮我解决这个问题吗?谢谢你。