Home » Java » spring – Java's Optional Forces Itself or else I get an error-Exceptionshub

spring – Java's Optional Forces Itself or else I get an error-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Why do I get an error if I don’t use Optional (the IDE suggested I use Optional) as oppose to just using DemographicEntity demoEntity?

@Test
public void testFindDemographicsById() {        
    DemographicEntity demoEntity = demoRepo.findById(1l); /////Gives Error  
}

@Test
public void testFindDemographicsById() {        
    /////forced to use Optional 
    Optional<DemographicEntity> demoEntity = demoRepo.findById(1l); /////No Error
}
How to&Answers:

Your findById returns an Optional. Use .get() in order to get the actual value

DemographicEntity demoEntity = demoRepo.findById(1l).get();

Answer:

In your demoRepo you must have had declared method

Optional<DemographicEntity> findById 

You can fix in two ways.

First one is to change method in repository to return DemographicEntity:

DemographicEntity findById

The other and better solution is to call

demoRepo.findById(1l).get();