Krishna
Krishna

Reputation: 1209

java.util.NoSuchElementException: No value present ; Apache cassandra - spring boot

I'm using the below dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>

I need to query on users table which is present in myks keyspace

From my controller part I'm calling the service

userService.authenticateUser(username, password);

And in the service method I have a call to repository

logger.info("Here : " + username);
boolean userExists = userRepository.existsById(username);
logger.info("userExists : " + userExists);
if (userExists) {
    User user = userRepository.findByusername(username).get();
    return user;
}
return null;

and the below is my repository

@Repository
public interface UserRepository extends CrudRepository<User, String> {
    Optional<User> findByusername(final String username);
}

Suppose in the table I don't have an entry with the user kri_test and user sends an input with the username kri_test then I'm facing the exception java.util.NoSuchElementException: No value present

Even it is not printing the log statements present in service class

Upvotes: 1

Views: 8145

Answers (2)

Sarmad Soz
Sarmad Soz

Reputation: 1

These are two controllers, so when we try to call any controller mostly we use URL for calling any kind of controller. 1.You might done mistake in URL or 2.you are trying to call that data which is not inside service class.

@RequestMapping("/topics")//URL
public List<Topic> getAllTopics() {
    return topicService.getAllTopics();     
}
@RequestMapping("/topics/{id}")
public Topic getTopic(@PathVariable String id){
    return topicService.getTopic(id);
}

Upvotes: 0

erolkaya84
erolkaya84

Reputation: 1849

It has nothing to do with Cassandra configuration etc. You are getting Optional.empty() from userRepository.findByusername(username). And you call get() method on that without calling isPresent() first.

You can fix your problem with this one liner;

return userRepository.findByusername(username).orElse(null);

Upvotes: 4

Related Questions