我正在服务类中测试一个delete方法,它不会从数据库中删除行。当我在应用程序运行时使用相同的方法时,它可以正常工作。我正在使用MySQL和H2database插件来测试该应用程序。其他CRUD测试方法也可以正常工作。
测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentAccountApplicationTests {
@Autowired
StudentAccountService studentAccountService;
@Test
public void testStudentAccountDeletion(){
Student student1 = new Student ("john","smith","studying");
Student student2 = new Student ("will","ferrel","finished");
Student student3 = new Student ("louis","johnsson","finished");
StudentAccount studentAccount1 = new StudentAccount ("josm","josm","studying", student1 );
StudentAccount studentAccount2 = new StudentAccount ("wife","wife","studying", student2);
StudentAccount studentAccount3 = new StudentAccount ("lojo","lojo","studying", student3);
studentService.save(student1);
studentService.save(student2);
studentService.save(student3);
studentAccountService.save(studentAccount1);
studentAccountService.save(studentAccount2);
studentAccountService.save(studentAccount3);
List<StudentAccount> studentAccountsToDelete = studentAccountService.getStudentAccountsFromFinishedStudents();
studentAccountService.deleteStudentAccountsFromFinishedStudents(studentAccountsToDelete);
List<StudentAccount> studentAccountsAfterDeletion = studentAccountService.getAllStudentAccounts();
assertEquals(1, studentAccountsAfterDeletion.size());
}
}
StudentAccountServiceImpl
public class StudentAccountServiceImpl implements StudentAccountService {
@Autowired
StudentAccountRepository studentAccountRepository;
@Override
public void deleteStudentAccount(StudentAccount studentToDelete) {
studentAccountRepository.delete(studentToDelete);
}
@Override
public void deleteStudentAccountsFromFinishedStudents(List<StudentAccount> studentAccountsToDelete) {
studentAccountsToDelete.forEach(studentAccount -> {
deleteStudentAccount(studentAccount);
});
}
}
该测试失败,因为未删除学生帐户,因此列表大小为3而不是1。如上所述,方法studentAccountsToDelete
在应用程序运行时正常工作。我不知道如果其他所有CRUD方法都起作用,这里有什么区别。我的猜测是H2database存在问题。需要一些帮助。预先感谢
答案 0 :(得分:0)
找到了解决方案。答案在发生映射的实体中。在实体中使用一对多映射时,这似乎是一个常见错误,因此
我更改了此内容:
@OneToMany(mappedBy = "student", cascade=CascadeType.ALL)
private Collection<StudentAccount> studentAccounts;
为此:
@OneToMany(mappedBy = "student", orphanRemoval=true)
private Collection<StudentAccount> studentAccounts;
请注意,我将cascade=CascadeType.ALL
替换为orphanRemoval=true
,这是在告诉休眠状态删除对不再存在的对象的引用。这对于清理依赖对象非常有用。以我为例,完成职业生涯的学生不再需要学生帐户。我希望这个答案对某人有帮助。
干杯