#why use Optional<MyClass> if you cant call any methods that MyClass has?

17 messages · Page 1 of 1 (latest)

sudden carbon
#

hey guys. can smb explain to me what wrong? im trying to retrieve an object from DB: Optional<Payment> earlierPayment=paymentRepository.findByTransactionIdAndAmount(paymentConfirmationRequest.getTransactionId(), paymentConfirmationRequest.getAmount());.

and for some reason i cant call any getters that my Payment entity has. does it mean that id need to change the return type of findByTransactionIdAndAmount from Optional<Payment> to just Payment? and then id loose the advantage Optional gives me. that doesnt make any sense 😦

any help? thanks

brittle swallowBOT
#

This post has been reserved for your question.

Hey @sudden carbon! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

solar scaffold
#

well, look at it this way

#

you ask the database to look up a thing by an id or something

#

obviously that thing might not exist, so at the repository level an Optional makes sense

#

Then in your service layer, you might actually need the thing to do something with

#

At that point, what do you do if you don't have the thing?

#

Can the method even continue?

#

If it can't, .orElseThrow, if it can .(flat)map

sudden carbon
#

wait a sec. it turns out that i can call .get() method on my Optional

#

and then id have the object, and then i could call the the metods my object has

north parcel
sudden carbon
#

but thanks for telling me that it can be a pitfall

brittle swallowBOT
north parcel