First, let me clarify that this is not a question asking "how to use" or "differences" of this method.
I have a query to lookup one object by ID in DB.
If this ID is invalid, no object will be returned, which will result in an error.
To prevent this from happening, I wrapped the return object in Optional, and the problem was solved.
At that moment, a new problem arose.
In the context of retrieving this object, I found that I had only two options.
Since there is an object returned, the object is used normally.
There is no object returned, so there is nothing we can do other than null or Throw.
My return object is UserEntity.
i.e. when i use the value
UserEntity user = getUser().orElstGet(null);
or
UserEntity user = getUser().orElstThrow(...);
I don't think there is anything else that can be done.
If the object I wanted didn't come in the response, UserEntity user; There is no object other than null that can be contained in .
Obviously something is wrong, or I think there is a more correct usage.
can you give me some advice?
You don't exactly give enough context to give a meaningful specific answer.
For users, a sensible usage could be
UserEntity user = userRepo.getUser(userId).orElseGet(() -> userRepo.getGuestUser());
It really depends on the use case.