So I do simple operation of finding an entry in my repository. If the entry is not present, the throw an exception.
@NotNull
public static User getUserFromUuid(UUID userUuid) {
Optional<User> userOptional = userRepository.findByUserIdentifier(userUuid);
if (!userOptional.isPresent()) {
if (logger.isInfoEnabled()) logger.info(String.format("Unable to find user with uuid %s", userUuid.toString()));
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User Not Found");
}
return userOptional.get();
}
@NotNull
public static Group getGroupFromId(Long groupId) {
Optional<Group> groupOptional = groupRepository.findById(groupId);
if (!groupOptional.isPresent()) {
if (logger.isInfoEnabled()) logger.info(String.format("Group with id %s does not exist", groupId));
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Group Not Found");
}
return groupOptional.get();
}
I realize I would end up doing this many times for all my find methods. And most of them will be doing a very similar task.
One way is to extend the CrudRepository
with my version, but I want to implement this pattern for al by finds.
Another way would be to pass the class, method, parameters, and the error message to search with. Lambda method seems to be the way, but I was unable to understand how I would be able to apply that to my problem.
This comes close to solving the problem, but the return type is changing. I would be passing a variable number of arguments as well.
Is there any approach I can take to do this?
EDIT:
I would also like to handle this case
Optional<GroupUser> groupUser = groupUserRepository.findByUserAndGroup(user, group
Where I could end up having more than one find parameters.
Something similar in python would be
def perform( fun, *args ):
fun( *args )
def action1( args ):
something
def action2( args ):
something
perform( action1 )
perform( action2, p )
perform( action3, p, r )