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);
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.
getSingleResult. Execute a SELECT query that returns a single untyped result.
getResultList() returns an empty list instead of null .
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);
}
}
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With