第一个断言语句通过但第二个断言未通过。逐步执行代码,数据库在每次提交时都会正确更新。但是,当辅助实体对象更新时,主实体似乎不会更新。
Entity secondary = (Entity) session.get(Entity.class, 2);
secondary.setPrimary(null);
session.beginTransaction();
session.save(secondary);
session.getTransaction().commit();
Entity primary = (Entity) session.get(Entity.class, 1);
secondary.setPrimary(primary);
session.beginTransaction();
session.save(secondary);
session.getTransaction().commit();
Set<Entity> secondarySet;
// If I comment out these two lines, the next assert passes.
secondarySet = primary.getSecondarySet();
assertFalse(secondarySet.isEmpty());
secondary.setPrimary(null);
session.beginTransaction();
session.save(secondary);
session.getTransaction().commit();
primary = (Entity) session.get(Entity.class, 1);
secondarySet = primary.getSecondarySet();
assertTrue(secondarySet.isEmpty());
我尝试了一些不成功的解决方案,例如将CascadeType.All添加到@OneToMany注释中,并刷新会话。一旦我的辅助实体保存并更改数据库,如何更新我的主要实体?
我的实体类看起来像:
@Entity
@DynamicInsert
@DynamicUpdate
@Table(catalog = "catalog", name = "Entity")
public class Entity implements java.io.Serializable {
private int id;
private Entity primary;
private Set<Entity> secondarySet;
public Entity() {
}
@Id
@Column(name = "ID_", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@OneToMany(mappedBy = "primary")
public Set<Entity> getSecondarySet() {
return this.secondarySet;
}
public void setSecondarySet(Set<Entity> secondarySet) {
this.secondarySet = secondarySet;
}
/**
* @return primary client if it exists, otherwise null
*/
@ManyToOne(cascade = CascadeType.ALL)
@NotFound(action = NotFoundAction.IGNORE) // can be it's own primary
@JoinTable(catalog = "catalog", name="entitylink",
joinColumns = {@JoinColumn(name="secondaryid_")},
inverseJoinColumns = {@JoinColumn(name="primaryid_")})
public Entity getPrimary() {
return this.primary;
}
public void setPrimary(Entity primary) {
this.primary = primary;
}
}