Issue
I want to know whether a given record is present in a database or not. so far I have achieved this by writing a JPA query and the running it by getSingleResult()
method. this would throw a NoResultException
if the record with the given parameter does not exist. Of course, it's not a must for the record to exist, so it's the normal behaviour sometimes, that's why I asked to myself, is it neccessary to throw an Exception which I have to handle by a catch block? As far as I know the cost of Exception handling is quite big, so I'm not very satisfied with this solution, also, I don't even need the object, I only need to know it's existence in the DB.
Is there a better way to check whether an object exist or not? eg. using getResultList()
and checking it's size maybe?
Solution
If you just want to know whether the object exists, send a SELECT COUNT
to your database. That will return 0 or 1.
The cost of the exception handling isn't that big (unless you do that millions of times during a normal operation), so I wouldn't bother.
But the code doesn't really reflect your intention. Since getSingleResult()
calls getResultList()
internally, it's clearer like so:
public boolean objExists(...) {
return getResultList(...).size() == 1;
}
If you query by object id and you have caching enabled, that will become a simple lookup in the cache if the object has already been loaded.
Answered By - Aaron Digulla
Answer Checked By - David Marino (JavaFixing Volunteer)