即使具有 orphanRemoval=true,孤儿也会保留在数据库中,在一对多关系 (JPA/Hibernate) 上也是如此
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "company_policies")
@DiscriminatorColumn(name = "rule_name")
public abstract class AbstractPolicyRule implements Serializable {
@Transient
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
private String value;
...
}
_
@Entity
public class Category implements Serializable {
@Transient
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(name = "category_name")
private String name;
@OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval = true)
@JoinColumn(name = "category_policy_id", referencedColumnName = "id")
private Set<AbstractPolicyRule> activePolicyRules;
...
}
更新此集时,现有的 activePolicyRules 在数据库中将其category_policy_id设置为 null,并插入新的策略。我想删除原始的。
我以为添加 orphanRemoval = true 会这样做,但事实并非如此。我看到的其他问题似乎具有双向关系,并且将父项设置为 null 可以解决它,但这不是双向关系。
有什么建议吗?
使用休眠 3.5.3
编辑:仅当数据库中存在现有的 AbstractPolicyRule 时,才会发生这种情况,我将其从列表中删除,然后再次保存类别。它的外键(category_policy_id)设置为 null,而不是被删除。
[DEBUG] Collection found: [domain.category.Category.activePolicyRules#1], was:
[<unreferenced>] (initialized)
[DEBUG] Flushed: 0 insertions, 2 updates, 0 deletions to 2 objects
[DEBUG] Flushed: 1 (re)creations, 0 updates, 1 removals to 1 collections
...
[DEBUG] Deleting collection: [domain.category.Category2.activePolicyRules#1]
[DEBUG] about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
[DEBUG] update company_policies set category_policy_id=null where category_policy_id=?
[DEBUG] done deleting collection
还尝试了联接表,因为Hibernate文档不鼓励使用上述方式:
@Entity
public class Category implements Serializable {
@Transient
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(name = "category_name")
private String name;
@OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL }, orphanRemoval = true)
@JoinTable(name = "policy_rule_mapping",
joinColumns = @JoinColumn(name = "category_id"),
inverseJoinColumns = @JoinColumn(name = "rule_id"))
private Set<AbstractPolicyRule> activePolicyRules;
...
}
这有同样的问题。映射表中的行将被删除,但抽象策略规则仍包含已删除的项。