I have been told that the standard for hibernate queries is to return each object wrapped in an Optional even when the return value is a List like so -
List<Optional<XEntity>> findAllByStatus(String status);
It makes complete sense that a single object should be wrapped in an Optional but I don't understand the reasoning when it is a list of objects (with an exception for a custom findAll()). If there is a null object, then it won't be picked up by the query, and if no objects correspond to the query, then an empty List would be returned. Adding an Optional for each item seems cumbersome and unnecessary.
I have been told by several people that using Optionals with List is a best practice but none gave me an sufficient explanation and I have been unable to find one via Google and I have yet to run into a problem while experimenting with
List<XEntity> findAllByStatus(String status);
CodePudding user response:
I agree with your point that wrapping up in Optional is good choice for single Object but in case of Collections like List,Set etc, it doesn't seems good choice to me. Especially when your API is ensuring to return a Collection object (List object or Empty List) every time. Since findAllByStatus(String status) ensures it will either return object(s) or no object in that case framework will ensure to return Empty List. Wrapping up every objects with Optional in list as you mentioned is only useful when any of the object in list is Null.
I have not seen any issue with List findAllByStatus(String status); yeah but I have seen people have used Optional<List> which is dangerous and inject run time exception.