ego
ego copied to clipboard
Fix N+1 select for Group entity graph
In the entity graph for Group entity, the call
group.getPermissions().get(0).getPolicy()
is possible with 1 select statement as defined with the named entity graph.
When
group.getPermissions().get(0).getPolicy().getGroupPermissions()
results in N select statements from the group permissions table. This was noticed in the addGroupPermissions method when adding a new groupPermission to an existing policy. The following code recreates the issue
val newGroupPermission = ...
val policyId = permissionRequest.getPolicyId();
// This will fetch a group using the defined named entity graph to load its child enitites
val group = groupRepository.getGroupByName("somenamne");
// No sql statments generated, as already loaded
val groupPermissions = group.getPermissions();
// Get the first polic with a matching policyId by filtering and transforming groupPermissions
val policy = groupPermissions.stream()
.map(x -> x.getPolicy())
.filter(x -> x.getId().equals(policyId))
.findFirst()
.get();
// Associate the new group permission bidirectionally with the group
group.getPermissions.add(newGroupPermission);
newGroupPermission.setOwner(group);
// Associate the new group permission bidirectionally with the policy
newGroupPermission.setPolicy(policy);
// This is where an extra select is made
policy.getGroupPermissions().add(newGroupPermission);
TLDR: When 1-2 selects should be made, more are made. Works now, but could be performance issue later. Investigate why more selects are being done. need to investigate optimization (hibernate, index db, cache)