Search code examples
javajpapersistenceeclipselink

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?


Solution

  • 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.