I have a method that returns an Optional value:
ublic Optional<Users> findByUserName(String name) {
String hqlRequest = "from Users U JOIN FETCH U.roles where U.name =:name";
Query query = sessionFactory.getCurrentSession().createQuery(hqlRequest).setParameter("name",name);
return Optional.ofNullable( (Users) query.getResultList().get(0) );
}
And when in another place I try to print the value
userService.findByUserName("admin2").ifPresent(System.out::println);
If I pass the correct name, then everything works, but why if the name is incorrect (the value is zero), then I get an error:
Caused by: java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
shouldn't this method skip null values?
CodePudding user response:
The Optional
doesn't even get created here. The IndexOutOfBoundsException will be coming from query.getResultList().get(0)
- you're trying to get the first element of an empty list, which doesn't exist.
Instead, you could return Optional.empty()
if the result list is empty.
CodePudding user response:
To get the desired behavior, i.e to get the first element of the result list, or an empty Optional if the result list is empty, change your return statement from
return Optional.ofNullable( (Users) query.getResultList().get(0) );
to
return query.getResultList().stream().map(Users.class::cast).findFirst();
CodePudding user response:
This method returns an instance of this Optional class with the specified value of the specified type.
If the specified value is null, then this method returns an empty instance of the Optional class.
So if the value is null, then it returns Optional.empty as output.
And when you do Optional.ofNullable( (Users) query.getResultList().get(0) );
You get the index out of bounds error.
You will have to first check if the value is not an empty instance of the optional class before you access data.