kfa*_*ria 2 spring-data spring-data-jpa
我对Spring引导数据和使用hibernate的JPA有很奇怪的行为.在我的实体CookbookRecipe被持久化之前,它被发现了CookBookRepository#findAll().
public interface CookbookRecipeRepository extends ExtendedJpaRepository<CookbookRecipe, Long> {}
Run Code Online (Sandbox Code Playgroud)
.
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
}
Run Code Online (Sandbox Code Playgroud)
测试
@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);
...
}
}
Run Code Online (Sandbox Code Playgroud)
食谱实体
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 );
}
}
Run Code Online (Sandbox Code Playgroud)
请注意assertThat(cookbookRecipeRepository.findAll().size(), is(0));哪个失败:
java.lang.AssertionError:
Expected: is <0>
but: was <1>
Run Code Online (Sandbox Code Playgroud)
您的示例中没有未提供的数据.触发查询(for findAll())会导致JPA持久性提供程序刷新您对托管实例(cookbook.addReceipe(…))所做的所有挂起更改.
除此之外,如果你有两个存储库Recipe,Cookbook它也不太可能有一个CookbookRecipeRepository.确保考虑聚合边界的位置,并仅为聚合根创建存储库.
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |