![](/img/trans.png)
[英]Hibernate removes child objects after session.update(parent)
[英]Hibernate with @CollectionTable removes the objects of set with same boolean value on update
我有以下结构:
public class Profile {
...
@ElementCollection(targetClass = ProfileFieldImpl.class, fetch = FetchType.EAGER)
@CollectionTable(name = "profileField", joinColumns = @JoinColumn(name = "profileId"))
@OrderColumn(name = "fieldName")
private Set<ProfileField> fields;
}
@Embeddable
public class ProfileFieldImpl {
@AttributeOverride(name = "id", column = @Column(name = "rofileFieldId", nullable = false))
private Long profileFieldId;
private String name;
}
现在,我添加一个新列: publicField还添加了equals
和hashCode
方法。
public class ProfileFieldImpl {
@AttributeOverride(name = "id", column = @Column(name = "rofileFieldId", nullable = false))
private Long profileFieldId;
private String name;
private boolean publicField;
@Override
public final boolean equals(final Object o) {
if (o == this) {
return true;
} else if (o == null || !(o instanceof ProfileFieldImpl)) {
return false;
} else {
final ProfileFieldImpl other = (ProfileFieldImpl) o;
return EqualsUtil.equalsNullable(getName(), other.getName()) && EqualsUtil.equalsNullable(isPublicField(), other.isPublicField()));
}
}
@Override
public final int hashCode() {
return HashCodeUtil.seed(HashCodeUtil.SEED_13).with(name).with(publicField).hashCode();
}
}
添加以下字段(数据库字段):
1. name = "Field1", publicField = '0'
2. name = "Field2", publicField = '0'
3. name = "Field3", publicField = '1'
4. name = "Field4", publicField = '1'
我如何进行更新:
....
final ProfileImpl profile = getEntityManager().find(Profile.java, profileId, LockModeType.NONE);
final Set<ProfileField> fields = profile.getFields();
fields.stream().filter(field -> field.getName().equals(currentFieldName)).forEach(field -> {
field.setName(updatedProfileField.getName());
field.setPublicField(updatedProfileField.isPublicField());
});
getEntityManager().merge(profile);
问题:
当我尝试更新field3
, field4
被删除; 当我尝试更新field1
, field2
被删除。
有人有什么建议吗?
听起来像个错误。 因此,您需要:
最后,我找到了问题以及解决方案 。
由于使用布尔值作为primitive
而不是object
因此出现了这个问题。
解决方案是使用布尔包装而不是原始包装。
private Boolean publicField;
现在可以正常工作,而不会删除任何其他对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.