我的问题不是“mappedBy”如何工作。我知道,只是表示关系的所有者。我的问题是 orphanRemoval 是如何工作的。在我的例子中,我根本不使用 mappedBy 指示。
我有以下实体:
@Entity
@Table(name = "catalog_orphan")
public class CatalogOrphan extends AbstractBaseEntity<Long> {
@OneToMany(orphanRemoval = true)
private List<GoodOrphan> goodOrphans;
public List<GoodOrphan> getGoodOrphans() {
return goodOrphans;
}
public void setGoodOrphans(List<GoodOrphan> goodOrphans) {
this.goodOrphans = goodOrphans;
}
}
@Entity
@Table(name = "good_orphan")
public class GoodOrphan extends AbstractBaseEntity<Long> {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "catalog_orphan_id")
private CatalogOrphan catalogOrphan;
public CatalogOrphan getCatalogOrphan() {
return catalogOrphan;
}
public void setCatalogOrphan(CatalogOrphan catalogOrphan) {
this.catalogOrphan = catalogOrphan;
}
}
@MappedSuperclass
public abstract class AbstractBaseEntity<ID> {
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected ID id;
@Column(name = "name")
protected String name;
}
我正在尝试测试删除孤儿的功能。
我写了以下测试:
@RunWith(SpringRunner.class)
@DataJpaTest
@TestExecutionListeners({
TransactionalTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class,
DbUnitTestExecutionListener.class
})
@DatabaseSetup("/persistCascade/orphan/catalog_good_orphan.xml")
public class CatalogOrphanTest {
@Autowired
protected TestEntityManager entityManager;
@Test
public void clearCollections() {
CatalogOrphan catalog = entityManager.find(CatalogOrphan.class, 1L);
catalog.getGoodOrphans().clear();
entityManager.persist(catalog);
entityManager.flush();
entityManager.clear();
CatalogOrphan catalogAfterCleanCollection2 = entityManager.find(CatalogOrphan.class, 1L);
assertThat(catalogAfterCleanCollection2.getGoodOrphans().size(), equalTo(0)); // Does this mean that the connection has been deleted?
GoodOrphan goodOrphan = entityManager.find(GoodOrphan.class, 1L);
assertThat(goodOrphan.getCatalogOrphan(), is(notNullValue())); // WHY???
}
}
catalog_good_orphan.xml:
<dataset>
<Catalog_Orphan id="1" name="Catalog#1"/>
<Catalog_Orphan id="2" name="Catalog#2"/>
<Good_Orphan id="1" name="Good#1" catalog_orphan_id="1"/>
<Good_Orphan id="2" name="Good#2" catalog_orphan_id="1"/>
<Good_Orphan id="3" name="Good#3" catalog_orphan_id="2"/>
<Good_Orphan id="4" name="Good#4" catalog_orphan_id="2"/>
<!-- without catalog -->
<Good_Orphan id="5" name="Good#5" />
</dataset>
我根本不明白“orphanRemoval = true”的意思。他为什么要那样工作?结果,我们只从“CatalogOrphan”中删除了“GoodOrphan”的链接,而“GoodOrphan”到“CatalogOrphan”的链接仍然存在。
我究竟做错了什么?还是这是正确的行为?