0

I'm trying to develop a simple crud application using Spring and Mongodb.

When I'm trying to develop view single data function, I get no error.

But it return value as null when I try in Postman.

Could you please help me to find what is the wrong with my code?

Controller

@GetMapping("/patient/{id}")
    public Optional<Patients> findTicketById(@PathVariable("id") @NotNull String id){
        System.out.println(id);
        return patientRepository.findById(id);
    }

Repository

@Repository
public interface PatientRepository extends MongoRepository<Patients, Long> {
    Optional<Patients> findById(String id);
}

enter image description here

  • @Repository public interface PatientRepository extends MongoRepository { Optional findById(String id); } Though I changed Repository by removing Long and adding String it also gives the same thing. – Malsha Madushani Kalahewaththa Jul 25 '21 at 07:32
  • You get `Optional` . So you need to first user `isPresent()` in if condition. Then you can use `get()` to get the object. And the post is not clear. You need to post the model class too.. Do yo have any parent mapping? (Is the id printing inside the method in System.out.println).. What is the query printing in the console? – varman Jul 25 '21 at 07:39
  • Have a look on Optional https://www.baeldung.com/java-optional – varman Jul 25 '21 at 07:41
  • Can you show the sample data inserted in your collection? – HandsomeCoder Jul 25 '21 at 09:31

1 Answers1

0

You can use ifPresentOrElse , check for the usages :

Functional style of Java 8's Optional.ifPresent and if-not-Present?