我有与另一个实体具有指定关系的实体Event
:
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "event")
private Set<Reminder> reminders = new HashSet<>();
一切正常(通过测试覆盖,检查了最重要的情况),直到我将version列添加到
Event
实体中。@Column(name = "version_num")
@Version
private long version;
添加
version
后,声明orphanRemoval
不再起作用(测试向我显示了)。 saveDefaultEventAndCalendar();
event.setReminders(Collections.emptySet());
eventRepository.save(event);
Event actualEvent = eventRepository.findOneByCalendarIdAndId(calendar.getId(), event.getId());
assertThat(actualEvent, equalTo(event));
assertThat(actualEvent.getReminders().size(), equalTo(0));
List<Reminder> reminders = reminderRepository.findAll();
assertThat(reminders.size(), equalTo(0));
由于
reminders
在db中,最后一行断言被破坏(reminders
链接到actualEvent
,但actualEvent
不再具有链接)。我希望能对这种修复帮助行为进行解释。
最佳答案
简单答案:
entityManager.flush();
详细答案:
解决方案的总体思路是使用新注入的
entityManager
推送级联更改,直到未关闭事务为止(级联更改在相关的特殊属性注释时休眠使用)。...
@PersistenceContext
private EntityManager entityManager;
...
@Test
public void save() {
saveDefaultEventAndCalendarFullyInitialized();
event1ForCalendar1.setReminders(Collections.emptySet());
eventRepository.save(event1ForCalendar1);
entityManager.flush();
Event actualEvent = eventRepository.findOneByCalendarIdAndId(calendar1.getId(), event1ForCalendar1.getId());
event1ForCalendar1.setVersion(event1ForCalendar1.getVersion() + 1);
assertThat(actualEvent, equalTo(event1ForCalendar1));
assertThat(actualEvent.getReminders().size(), equalTo(0));
List<Reminder> reminders = reminderRepository.findAll();
assertThat(reminders.size(), equalTo(0));
}