这可能与我几天前的问题有关,但我什至不确定如何解释这部分。(这是完全不同的亲子关系。)
在我的界面中,我有一组属性(Attribute)和有效值(ValidValue),每个属性都是一对多的关系。在 Spring MVC 前端,我有一个页面供管理员编辑这些值。提交后,如果这些字段(作为 <input> 标记)中的任何一个为空白,我将删除 ValidValue 对象,如下所示:
Set<ValidValue> existingValues = new HashSet<ValidValue>(attribute.getValidValues());
Set<ValidValue> finalValues = new HashSet<ValidValue>();
for(ValidValue validValue : attribute.getValidValues()) {
if(!validValue.getValue().isEmpty()) {
finalValues.add(validValue);
}
}
existingValues.removeAll(finalValues);
for(ValidValue removedValue : existingValues) {
getApplicationDataService().removeValidValue(removedValue);
}
attribute.setValidValues(finalValues);
getApplicationDataService().modifyAttribute(attribute);
问题是,虽然数据库得到了适当的更新,但下次我查询 Attribute 对象时,它们会在其 ValidValue 集中返回一个额外的条目——一个空值,因此,下次我遍历这些值时显示,它在中间显示一个额外的空白值。我已经确认这发生在合并或查找时,在“执行查询 ReadObjectQuery(entity.Attribute).
这是我用来修改数据库的代码(在 ApplicationDataService 中):
public void modifyAttribute(Attribute attribute) {
getJpaTemplate().merge(attribute);
}
public void removeValidValue(ValidValue removedValue) {
ValidValue merged = getJpaTemplate().merge(removedValue);
getJpaTemplate().remove(merged);
}
以下是实体类的相关部分:
Entity
@Table(name = "attribute")
public class Attribute {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "attribute")
private Set<ValidValue> validValues = new HashSet<ValidValue>(0);
}
@Entity
@Table(name = "valid_value")
public class ValidValue {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "attr_id", nullable = false)
private Attribute attribute;
}