Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a record exists using JPA

Tags:

java

jpa

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?

like image 555
Balázs Németh Avatar asked Dec 07 '10 08:12

Balázs Németh


People also ask

What is Criteriabuilder in JPA?

CriteriaBuilderJPA interfaceUsed to construct criteria queries, compound selections, expressions, predicates, orderings. See JavaDoc Reference Page... interface serves as the main factory of criteria queries and criteria query elements. It can be obtained either by the EntityManagerFactory. persistence.

How do you find out if a record already exists in a database if it doesn't insert a new record in Java?

Another option (still keeping the unique constraint) would be to make a more complicated SQL insert statement that inserts only if not existing, you may google "sql insert if not exist" to find some examples... Show activity on this post. You need to get the appropriate record from the ResultSet e.g.

What is the difference between CrudRepository and JpaRepository?

CrudRepository mainly provides CRUD operations. PagingAndSortingRepository provide methods to perform pagination and sorting of records. JpaRepository provides JPA related methods such as flushing the persistence context and deleting of records in batch.


2 Answers

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.

like image 181
Aaron Digulla Avatar answered Sep 30 '22 18:09

Aaron Digulla


Try to avoid loading the entity into the session (getSingleResult()) just to check for it's existence. A count is better here. With the Criteria Query API it would look something like this:

public <E extends AbstractEntity> boolean exists(final Class<E> entityClass, final int id) {     final EntityManager em = getEntityManager();     final CriteriaBuilder cb = em.getCriteriaBuilder();      final CriteriaQuery<Long> cq = cb.createQuery(Long.class);     final Root<E> from = cq.from(entityClass);      cq.select(cb.count(from));     cq.where(cb.equal(from.get(AbstractEntity_.id), id));      final TypedQuery<Long> tq = em.createQuery(cq);     return tq.getSingleResult() > 0; } 
like image 26
Radu Avatar answered Sep 30 '22 18:09

Radu