Ilia Tapia
Ilia Tapia

Reputation: 649

How to write a properly query in hibernate?

I have

    PartnerNotification quest = partnerNotificationRepository.findById(login.getAccount().getAccountId());

but doesn't work I get this error

Type mismatch: cannot convert from Optional<PartnerNotification> to PartnerNotification 

and I don't really get why is this happening, does anyone have a clue what is going one and how can I fix it? AS I don't know what is wrong here I tried to create a query on my own but still, I am missing something here in the syntax :

/**
 * @param partnerId .
 * @return Notification
 */
@Query("SELECT  FROM PartnerNotification  WHERE  partner_id = :partnerId")
PartnerNotification findNotificationByPartnerId(@Param("partnerId") Integer partnerId);

any help is appreciated and it will be helpful!

Upvotes: 0

Views: 62

Answers (1)

I think you should implement it.

Example:

Repository:

@Query("SELECT  FROM PartnerNotification  WHERE  partner_id = :partnerId")
Optional<PartnerNotification> findNotificationByPartnerId(@Param("partnerId") Integer partnerId);

Service:

PartnerNotification quest = partnerNotificationRepository.findById(login.getAccount().getAccountId())
.orElseThrow(RuntimeException::new);

Note: you can use another solution and another Exception when accountId is not found. Or you can use if else statement (e.g.: isPresent() )

Upvotes: 1

Related Questions