我的问题不是“ 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”的链接。
我在做什么错?还是这是正确的行为?
答案 0 :(得分:1)
removeOrphan当不再与父项链接时,会将其从数据库中删除。仅当您在同一会话中从列表中删除该项目时,它才起作用。注意:从列表中删除和从项目中删除对父项的引用是两个不同的事情,即使您(应该)在数据库中为这两个引用使用相同的外键。
注意:当您从一个列表中删除一个项目并将其添加到另一个列表时,此功能不起作用。幸运的话,您会收到一个异常消息,告诉您它不起作用。