JPA and deprecated getOne() and getById() -> how to catch EntityNotFoundException in getReferenceById

Viewed 299

In other similar questions on how to catch EntityNotFoundException the main tip was to use simpler methods that return null like getOne

As of spring-boot v 2.7 + both getOne() and getById() are marked as deprecated and documentation says to use getReferenceById instead.

The Problem as mentioned in some other question, that you can't simply catch javax.persistence.EntityNotFoundException.

This is never be caught:

    fun getDonation(donationId: Long): DonationDto? {
        return try{
            val entity: DonationEntity = donationJpaRepository.getById(donationId)
            mapper.toDonationDto(entity)
        } catch (e : EntityNotFoundException){
            null
        }

    }

Apart from downgrading the version and moving on with my life, how do I get to catch the exception or handle not found entities?

1 Answers

Seems like you can catch JpaObjectRetrievalFailureException in this case.

From the documentation to JpaObjectRetrievalFailureException

JPA-specific subclass of ObjectRetrievalFailureException. Converts JPA's EntityNotFoundException.

  return try {
            val dto = service.getStuff(id)
            ResponseEntity(dto, HttpStatus.OK)
        } catch (e: JpaObjectRetrievalFailureException) {
            ResponseEntity("Nothing with id $id.", HttpStatus.NOT_FOUND)
        }

Related