[英]Reusable lazy loading with hibernate
Here are some methods I have in my UserRepository
class : 这是我在
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);
These methods all have something like bellow to determine the relations to be loaded: 这些方法都具有类似以下的功能,可以确定要加载的关系:
// An example for getWithRoles(Long userId);
criteria.setFetchMode("roles", FetchMode.JOIN);
I did my best to not duplicate codes between these methods but it is still hard to maintain IMO. 我已尽力在这些方法之间不重复代码,但是仍然很难维护IMO。
Is there a way to avoid this and end up with something like bellow? 有办法避免这种情况并以类似波纹管的形式结束吗?
userRepo.findOne(userId)
.withRelation(User_.roles)
.withRelation(User_.posts);
userRepo.findOne(userId)
.withRelation(User_.roles)
.withRelation(User_.activities);
userRepo.findOne(userId)
.withAllRelations();
I'm basically looking for a way to reuse relations-fetcher methods without rewriting a whole new method just for that. 我基本上是在寻找一种方法来重用关系获取器方法,而不必为此重写一个全新的方法。
PS: In the example above, User_
is a JPA Static Metamodel PS:在上面的示例中,
User_
是JPA静态元模型
I think I just found an idea to implement this in the repository. 我想我刚刚找到了在存储库中实现此想法的想法。
I just need to pass a list of attributes as a second argument. 我只需要传递一个属性列表作为第二个参数。
get(Long userId, List<String> relations);
Or even better 甚至更好
get(Long userId, List<Attribute> relations);
The implementation of this will loop through the relations argument, and fetch them one by one. 此操作的实现将循环调用关系参数,并逐个获取它们。
The difficult part is when I have to deal with nested relations. 困难的部分是当我必须处理嵌套关系时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.