Check if JPA entity exists without loading it

The problem is following.

We have a server endpoint, that receives feedback from clients. Feedback received in multipart/form-based format, with fields:

ProductId - product identifier
Message - feedback message
Log_file - attached log file
Screenshot - attached screenshot file

Server code first checks if the product with given id exists and if not - closes connection without receiving any attached files.

We use Eclipselink JPA to store product objects.

How it's possible to check if a product with given id exists without loading it from underlying database?

Upvotes: 3

Views: 8448

Answers (2)

Chris
Chris

Reputation: 21155

What are you trying to avoid exactly? JPA allows lazy loading of pretty much every field in the entity, so what you get back may or may not be loaded. A simple EntityManager.find operation will retrieve the entity from the cache if it exists there, and if not, check the database, so for most situations this might be enough. If it goes to the database, it will then build an instance and put it in the cache, but that instance will only include eager mappings.

Otherwise, you can avoid the loading using any JPA query that returns data rather than an entity instance, but this will require a database hit. The count option above is one way, but a simple "Select e.id from Employee e where e.id =:empId" will work as well.

Upvotes: 3

Salih Erikci
Salih Erikci

Reputation: 5087

You can use count to see if any row with the id will be returned.

em.createQuery(
    "SELECT COUNT(b.productId) 
    FROM Products b WHERE b.productId=:productId"
);

If count < 1 there is no product with that id. Else there is a product with that id.

Upvotes: 5

Related Questions