简体   繁体   English

Hibernate如何在OneToMany关系中将null设置为外键列

[英]How to set null to foreign key column in OneToMany relationship, Hibernate

I have 2 classes: User and Company. 我有2个班级:用户和公司。

User
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "company_id")
public Company getCompany() {
    return company;
}

Company
@OneToMany(mappedBy = "company", fetch = FetchType.LAZY)
public List<User> getEmployees() {
        return employees;
}

I need when I delete Company to set foreign key company_id as null in User table. 删除公司时,需要在User表中将外键company_id设置为null。 How could I do this? 我该怎么办?

Typically the relationship you describe would be created with a constraint on the Foreign Key that references the User entity. 通常,您描述的关系将在对引用User实体的外键上具有constraint情况下创建。 This is so you can't set it to null . 因此,您不能将其设置为null If you set it to null, it becomes an orphaned row, which makes for a bad database. 如果将其设置为null,它将成为orphaned行,这将导致数据库损坏。

If, on the other hand, you need the two entities to persist separately from their joins, then your relationship is not as you are describing it. 另一方面,如果您需要两个实体与其连接分开持久存在,那么您的关系就不像您描述的那样。

It seems that in this case Companies and Users (Persons?) both need to exist without necessarily being joined. 在这种情况下,似乎公司和用户(人员?)都需要存在而不必加入。 I would suggest a new entity, something like Employment . 我建议一个新的实体,例如“ Employment It would effectively act as a join table in the sense that it has both Company and User id's, but it could also have more information such as startdate , enddate , and current employer . 从具有CompanyUser ID的意义上说,它可以有效地充当join table ,但是它也可以具有更多信息,例如startdateenddatecurrent employer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM