diff --git a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/QueryImpl.java b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/QueryImpl.java index 5def74057..18ce2987a 100644 --- a/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/QueryImpl.java +++ b/openjpa-persistence/src/main/java/org/apache/openjpa/persistence/QueryImpl.java @@ -281,14 +281,26 @@ public class QueryImpl */ public Object getSingleResult() { _em.assertNotCloseInvoked(); - // temporarily set query to unique so that a single result is validated - // and returned; unset again in case the user executes query again - // via getResultList - _query.setUnique(true); + Object ob = execute(); + if (!(ob instanceof List)) + return ob; + + List res = (List) ob; try { - return execute(); + // don't use size() b/c can be inefficient under some LRS settings + Iterator itr = res.iterator(); + if (!itr.hasNext()) + throw new NoResultException(_loc.get("no-results", + _query.getQueryString()).getMessage(), null, null, false); + + Object ret = itr.next(); + if (itr.hasNext()) + throw new NonUniqueResultException(_loc.get("mult-results", + _query.getQueryString()).getMessage(), null, null, false); + + return ret; } finally { - _query.setUnique(false); + OpenJPAPersistence.close(res); } }