[英]Reusable lazy loading with hibernate
這是我在UserRepository
類中擁有的一些方法:
// Get a user with all his roles
getWithRoles(Long userId);
// Get a user with all his posts
getWithPosts(Long userId);
// Get a user with all his activities
getWithActivities(Long userId);
// Get a user with all his relations
getWithAllRelations(Long userId);
這些方法都具有類似以下的功能,可以確定要加載的關系:
// An example for getWithRoles(Long userId);
criteria.setFetchMode("roles", FetchMode.JOIN);
我已盡力在這些方法之間不重復代碼,但是仍然很難維護IMO。
有辦法避免這種情況並以類似波紋管的形式結束嗎?
userRepo.findOne(userId)
.withRelation(User_.roles)
.withRelation(User_.posts);
userRepo.findOne(userId)
.withRelation(User_.roles)
.withRelation(User_.activities);
userRepo.findOne(userId)
.withAllRelations();
我基本上是在尋找一種方法來重用關系獲取器方法,而不必為此重寫一個全新的方法。
PS:在上面的示例中, User_
是JPA靜態元模型
我想我剛剛找到了在存儲庫中實現此想法的想法。
我只需要傳遞一個屬性列表作為第二個參數。
get(Long userId, List<String> relations);
甚至更好
get(Long userId, List<Attribute> relations);
此操作的實現將循環調用關系參數,並逐個獲取它們。
困難的部分是當我必須處理嵌套關系時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.