diff --git a/core/src/main/java/org/sql2o/Query.java b/core/src/main/java/org/sql2o/Query.java index a62c4198..b1929f01 100644 --- a/core/src/main/java/org/sql2o/Query.java +++ b/core/src/main/java/org/sql2o/Query.java @@ -577,6 +577,26 @@ public ResultSetHandler newResultSetHandler(ResultSetMetaData resultSetMetaDa }; } + public T executeAndFetchUnique(Class returnType){ + return executeAndFetchUnique( newResultSetHandlerFactory( returnType ) ); + } + + public T executeAndFetchUnique(ResultSetHandler resultSetHandler){ + return executeAndFetchUnique( newResultSetHandlerFactory( resultSetHandler ) ); + } + + public T executeAndFetchUnique(ResultSetHandlerFactory factory) { + List list = executeAndFetch( factory ); + int size = list.size(); + if( size > 1 ) { + throw new Sql2oException( "Expected 0..1 results, found: " + list.size() ); + } + if( size == 0 ){ + return null; + } + return list.get( 0 ); + } + public List executeAndFetch(Class returnType){ if (returnType.isPrimitive() || Arrays.stream(primitives).anyMatch(n -> returnType.equals(n))) { diff --git a/core/src/test/java/org/sql2o/Sql2oTest.java b/core/src/test/java/org/sql2o/Sql2oTest.java index 87225d54..61893005 100644 --- a/core/src/test/java/org/sql2o/Sql2oTest.java +++ b/core/src/test/java/org/sql2o/Sql2oTest.java @@ -102,6 +102,33 @@ public void testExecuteAndFetch(){ deleteUserTable(); } + @Test + public void testExecuteAndFetchUniqueWhenUnique(){ + createAndFillUserTable(); + + try (Connection con = sql2o.open()) { + + User user = con.createQuery("select * from user_table u where u.id = 1").executeAndFetchUnique(User.class); + + assertNotNull(user); + } + + deleteUserTable(); + } + + @Test(expected = Sql2oException.class) + public void testExecuteAndFetchUniqueWhenNotUnique(){ + createAndFillUserTable(); + + try (Connection con = sql2o.open()) { + + User user = con.createQuery("select * from user_table u where u.id > 0").executeAndFetchUnique(User.class); + } + finally { + deleteUserTable(); + } + } + @Test public void testExecuteAndFetchWithNulls(){ String sql =