0

This excellent question and answer define when to use EntityManager#find v. #getReference with this answer.

This question elaborates on the behavior of getting, and then updating an object.

But, I'm only interested in determining whether my javax.persistence.Entity exists for a particular id.

Is EntityManager#getReference more efficient than EntityManager#find?

I'm looking for the light-weight way to find whether an id exists for a given Entity.

Community
  • 1
  • 1
Kevin Meredith
  • 38,251
  • 58
  • 190
  • 340

1 Answers1

0

Write your own utility class for that, with a query like:

SELECT id FROM EntityClass where id= ?

and then simply call query.getSingleResult() trying/catching a NoResultExceptionfor the case no result is available (or query.getResultList() and checking the count()).

Selecting the ID only makes sure, that the minimal needed data is fetched from DB, instead of fully fetching the entity with its related entities.

Andrei I
  • 18,090
  • 6
  • 46
  • 81