我对Spring引导数据和使用hibernate的JPA有很奇怪的行为。在我的实体CookbookRecipe
被保留之前,CookBookRepository#findAll().
public interface CookbookRecipeRepository extends ExtendedJpaRepository<CookbookRecipe, Long> {}
public class ExtendedJpaRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements ExtendedJpaRepository<T, ID> {
// added a new helper method, but certainly not overridden findAll
}
测试
@RunWith(SpringRunner.class)
@DataJpaTest
public class CookbookRepositoryIntegrationTest {
@Autowired
RecipeRepository recipeRepository;
@Autowired
CookbookRepository cookbookRepository;
@Autowired
CookbookRecipeRepository cookbookRecipeRepository;
@Test
public void WhenAddingSameAssociationAgain_ThenNoException() {
Recipe recipe = new Recipe();
recipe.setTitle("A Recipe");
recipe = recipeRepository.save(recipe);
Cookbook cookbook = new Cookbook();
cookbook.setTitle("A Cookbook");
cookbook = cookbookRepository.save(cookbook);
cookbook.addRecipe(recipe, "integrationtest", new Date());
assertThat(cookbookRecipeRepository.findAll().size(), is(0));
cookbook = cookbookRepository.save(cookbook);
...
}
}
食谱实体
public void addRecipe(Recipe recipe, String createdBy, Date createdDate) {
final CookbookRecipe cookbookRecipe = new CookbookRecipe(this, recipe);
cookbookRecipe.setCreatedBy(createdBy);
cookbookRecipe.setCreatedDate(createdDate);
if( !cookbookRecipes.contains(cookbookRecipe) && !recipe.getCookbookRecipes().contains(cookbookRecipe)) {
cookbookRecipes.add(cookbookRecipe);
recipe.getCookbookRecipes().add( cookbookRecipe );
}
}
请注意失败的assertThat(cookbookRecipeRepository.findAll().size(), is(0));
:
java.lang.AssertionError:
Expected: is <0>
but: was <1>
答案 0 :(得分:5)
您的示例中没有未经加载的数据。触发查询(对于findAll()
)会导致JPA持久性提供程序刷新您对托管实例(cookbook.addReceipe(…)
)所做的所有挂起更改。
除此之外,如果您有Recipe
和Cookbook
的存储库,那么它也不太可能有一个CookbookRecipeRepository
。确保考虑聚合边界的位置,并仅为聚合根创建存储库。