Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is better: getSingleResult, or getResultList JPA

Tags:

jpa

i need to retrieve single row from table, and i was interested what approach is better. On the one side getSingleResult is designed for retrieving single result, but it raises exception. Does this method have benefit in performance related to getResultList with

query.setFirstResult(0);
query.setMaxResults(1); 
like image 519
Andrey Avatar asked Dec 14 '11 05:12

Andrey


People also ask

When to use getSingleResult?

getSingleResult throws NonUniqueResultException, if there are multiple rows or no any rows . It is designed to retrieve single result when there is truly a single result. Show activity on this post. In combination with fetch() the usage of setMaxResults(1) can lead to a partially initialised objects.

What does getSingleResult do?

getSingleResult. Execute a SELECT query that returns a single untyped result.

Can getResultList return null?

getResultList() returns an empty list instead of null .


3 Answers

According to Effective Java by Joshua Bloch:

Use checked exceptions for conditions from wich the caller can reasonably be expected to recover. Use runtime exceptions to indicate programming errors.

Credit to the source: Why you should never use getSingleResult() in JPA

@Entity
@NamedQuery(name = "Country.findByName", 
            query = "SELECT c FROM Country c WHERE c.name = :name"
public class Country {
  @PersistenceContext
  transient EntityManager entityManager;

  public static Country findByName(String name) {
      List<Country> results = entityManager
            .createNamedQuery("Country.findByName", Country.class)
            .setParameter("name", name).getResultList();
      return results.isEmpty() ? null : results.get(0);
  }
}
like image 121
Tomasz Avatar answered Oct 19 '22 22:10

Tomasz


getSingleResult throws NonUniqueResultException, if there are multiple rows. It is designed to retrieve single result when there is truly a single result.

The way you did is fine and JPA is designed to handle this properly. At the same time, you cannot compare it against getSingleResult any way, since it won't work.

However, depend on the code you are working on, it is always better to refine the query to return single result, if that's all what you want - then you can just call getSingleResult.

like image 10
勿绮语 Avatar answered Oct 19 '22 22:10

勿绮语


There is an alternative which I would recommend:

Query query = em.createQuery("your query");
List<Element> elementList = query.getResultList();
return CollectionUtils.isEmpty(elementList ) ? null : elementList.get(0);

This safeguards against Null Pointer Exception, guarantees only 1 result is returned.

like image 3
aces. Avatar answered Oct 19 '22 21:10

aces.