From af2550bb054bc9ec79aa02d9fa1953765b930da0 Mon Sep 17 00:00:00 2001 From: Marc Prud'hommeaux Date: Fri, 6 Apr 2007 23:52:03 +0000 Subject: [PATCH] OPENJPA-208 Throw NoResultException and NonUniqueResultException when expected git-svn-id: https://svn.apache.org/repos/asf/incubator/openjpa/trunk@526322 13f79535-47bb-0310-9956-ffa450edef68 --- .../apache/openjpa/persistence/QueryImpl.java | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) 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); } }