春天懒加载嵌套事务内部不工作
我用kotlin。 这是我的实体类:
@Entity class Category( @Id @GeneratedValue(strategy = IDENTITY) val id: Int = 0, @NotBlank @Column(unique = true) var name: String, @OneToMany(mappedBy = "category") val subcategories: MutableSet<Subcategory> = mutableSetOf() ) @Entity class Subcategory( @Id @GeneratedValue(strategy = IDENTITY) val id: Int = 0, @NotBlank var name: String, @ManyToOne val category: Category )
服务方式:
@Transactional fun addSubcategory(model: CreateSubcategoryModel): SubcategoryDto { return categoryRepository.findOne(model.categoryId) ?.let { it.subcategories.find { it.name.equals(other = model.name, ignoreCase = true) } .apply { if(this != null) throw SubcategoryAlreadyExistException() } subcategoryRepository.save(Subcategory(name = model.name!!, category = it)).let { SubcategoryDto.parse(it) } } ?: throw CategoryNotFoundException() }
我有简单的测试,测试是否可以添加现有名称的子类别:
@Test fun `given existing subcategory when add subcategory expect exception`() { //given val category = categoryService.addCategory(CreateCategoryModel(name = "category")) val createSubcategoryModel = CreateSubcategoryModel(name = "subcategory", categoryId = category.id) categoryService.addSubcategory(createSubcategoryModel) //when && then assertThatThrownBy { categoryService.addSubcategory(createSubcategoryModel) } .isInstanceOf(SubcategoryAlreadyExistException::class.java) }
我的测试课用以下注释注释:
@RunWith(SpringRunner::class) @SpringBootTest
当我使用下面的注释运行这个测试时,它可以正常工作,但它将实体保存到我的数据库,并且不会回滚这些更改。 我读到了将@Transactional添加到我的测试方法以回滚更改,但是将其添加到测试方法后,该测试不起作用,因为子类不从db中提取,并且不引发异常。 有没有其他的方法来测试这个方法,或者当我的服务方法中添加子类别时,我做错了什么?