Java Code Examples for org.springframework.dao.IncorrectResultSizeDataAccessException

The following examples show how to use org.springframework.dao.IncorrectResultSizeDataAccessException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-analysis-note   Source File: DataAccessUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Return a unique result object from the given Collection.
 * Throws an exception if 0 or more than 1 result objects found,
 * of if the unique result object is not convertible to the
 * specified required type.
 * @param results the result Collection (can be {@code null}
 * but is not expected to contain {@code null} elements)
 * @return the unique result object
 * @throws IncorrectResultSizeDataAccessException if more than one
 * result object has been found in the given Collection
 * @throws EmptyResultDataAccessException if no result object
 * at all has been found in the given Collection
 * @throws TypeMismatchDataAccessException if the unique object does
 * not match the specified required type
 */
@SuppressWarnings("unchecked")
public static <T> T objectResult(@Nullable Collection<?> results, @Nullable Class<T> requiredType)
		throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException {

	Object result = requiredUniqueResult(results);
	if (requiredType != null && !requiredType.isInstance(result)) {
		if (String.class == requiredType) {
			result = result.toString();
		}
		else if (Number.class.isAssignableFrom(requiredType) && Number.class.isInstance(result)) {
			try {
				result = NumberUtils.convertNumberToTargetClass(((Number) result), (Class<? extends Number>) requiredType);
			}
			catch (IllegalArgumentException ex) {
				throw new TypeMismatchDataAccessException(ex.getMessage());
			}
		}
		else {
			throw new TypeMismatchDataAccessException(
					"Result object is of type [" + result.getClass().getName() +
					"] and could not be converted to required type [" + requiredType.getName() + "]");
		}
	}
	return (T) result;
}
 
Example 2
Source Project: spring-analysis-note   Source File: DataAccessUtilsTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("deprecation")  // on JDK 9
public void withEquivalentIntegerInstanceTwice() {
	Collection<Integer> col = new ArrayList<>(2);
	col.add(new Integer(5));
	col.add(new Integer(5));

	try {
		DataAccessUtils.uniqueResult(col);
		fail("Should have thrown IncorrectResultSizeDataAccessException");
	}
	catch (IncorrectResultSizeDataAccessException ex) {
		// expected
		assertEquals(1, ex.getExpectedSize());
		assertEquals(2, ex.getActualSize());
	}
}
 
Example 3
Source Project: java-technology-stack   Source File: DataAccessUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Return a unique result object from the given Collection.
 * Throws an exception if 0 or more than 1 result objects found,
 * of if the unique result object is not convertible to the
 * specified required type.
 * @param results the result Collection (can be {@code null}
 * but is not expected to contain {@code null} elements)
 * @return the unique result object
 * @throws IncorrectResultSizeDataAccessException if more than one
 * result object has been found in the given Collection
 * @throws EmptyResultDataAccessException if no result object
 * at all has been found in the given Collection
 * @throws TypeMismatchDataAccessException if the unique object does
 * not match the specified required type
 */
@SuppressWarnings("unchecked")
public static <T> T objectResult(@Nullable Collection<?> results, @Nullable Class<T> requiredType)
		throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException {

	Object result = requiredUniqueResult(results);
	if (requiredType != null && !requiredType.isInstance(result)) {
		if (String.class == requiredType) {
			result = result.toString();
		}
		else if (Number.class.isAssignableFrom(requiredType) && Number.class.isInstance(result)) {
			try {
				result = NumberUtils.convertNumberToTargetClass(((Number) result), (Class<? extends Number>) requiredType);
			}
			catch (IllegalArgumentException ex) {
				throw new TypeMismatchDataAccessException(ex.getMessage());
			}
		}
		else {
			throw new TypeMismatchDataAccessException(
					"Result object is of type [" + result.getClass().getName() +
					"] and could not be converted to required type [" + requiredType.getName() + "]");
		}
	}
	return (T) result;
}
 
Example 4
/**
 * @see SearchableJobExecutionDao#getJobExecutions(String, int, int)
 */
@Override
public List<JobExecution> getJobExecutions(String jobName, int start, int count) {
    if (start <= 0) {
        return getJdbcTemplate().query(byJobNamePagingQueryProvider.generateFirstPageQuery(count),
                new JobExecutionRowMapper(), jobName);
    }
    try {
        Long startAfterValue = getJdbcTemplate().queryForObject(
                byJobNamePagingQueryProvider.generateJumpToItemQuery(start, count), Long.class, jobName);
        return getJdbcTemplate().query(byJobNamePagingQueryProvider.generateRemainingPagesQuery(count),
                new JobExecutionRowMapper(), jobName, startAfterValue);
    }
    catch (IncorrectResultSizeDataAccessException e) {
        return Collections.emptyList();
    }
}
 
Example 5
/**
 * @see SearchableJobExecutionDao#getJobExecutions(int, int)
 */
@Override
public List<JobExecution> getJobExecutions(int start, int count) {
	if (start <= 0) {
		return getJdbcTemplate().query(allExecutionsPagingQueryProvider.generateFirstPageQuery(count),
				new JobExecutionRowMapper());
	}
	try {
		Long startAfterValue = getJdbcTemplate().queryForObject(
				allExecutionsPagingQueryProvider.generateJumpToItemQuery(start, count), Long.class);
		return getJdbcTemplate().query(allExecutionsPagingQueryProvider.generateRemainingPagesQuery(count),
				new JobExecutionRowMapper(), startAfterValue);
	}
	catch (IncorrectResultSizeDataAccessException e) {
		return Collections.emptyList();
	}
}
 
Example 6
Source Project: lams   Source File: DataAccessUtils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return a unique result object from the given Collection.
 * Throws an exception if 0 or more than 1 result objects found,
 * of if the unique result object is not convertible to the
 * specified required type.
 * @param results the result Collection (can be {@code null})
 * @return the unique result object
 * @throws IncorrectResultSizeDataAccessException if more than one
 * result object has been found in the given Collection
 * @throws EmptyResultDataAccessException if no result object
 * at all has been found in the given Collection
 * @throws TypeMismatchDataAccessException if the unique object does
 * not match the specified required type
 */
@SuppressWarnings("unchecked")
public static <T> T objectResult(Collection<?> results, Class<T> requiredType)
		throws IncorrectResultSizeDataAccessException, TypeMismatchDataAccessException {

	Object result = requiredUniqueResult(results);
	if (requiredType != null && !requiredType.isInstance(result)) {
		if (String.class == requiredType) {
			result = result.toString();
		}
		else if (Number.class.isAssignableFrom(requiredType) && Number.class.isInstance(result)) {
			try {
				result = NumberUtils.convertNumberToTargetClass(((Number) result), (Class<? extends Number>) requiredType);
			}
			catch (IllegalArgumentException ex) {
				throw new TypeMismatchDataAccessException(ex.getMessage());
			}
		}
		else {
			throw new TypeMismatchDataAccessException(
					"Result object is of type [" + result.getClass().getName() +
					"] and could not be converted to required type [" + requiredType.getName() + "]");
		}
	}
	return (T) result;
}
 
Example 7
/**
 * @see SearchableJobExecutionDao#getJobExecutionsWithStepCount(String, int, int)
 */
@Override
public List<JobExecutionWithStepCount> getJobExecutionsWithStepCount(String jobName, int start, int count) {
	if (start <= 0) {
		return getJdbcTemplate().query(byJobNameWithStepCountPagingQueryProvider.generateFirstPageQuery(count),
				new JobExecutionStepCountRowMapper(), jobName);
	}
	try {
		Long startAfterValue = getJdbcTemplate().queryForObject(
				byJobNameWithStepCountPagingQueryProvider.generateJumpToItemQuery(start, count), Long.class, jobName);
		return getJdbcTemplate().query(byJobNameWithStepCountPagingQueryProvider.generateRemainingPagesQuery(count),
				new JobExecutionStepCountRowMapper(), jobName, startAfterValue);
	}
	catch (IncorrectResultSizeDataAccessException e) {
		return Collections.emptyList();
	}
}
 
Example 8
@Test
public void withEquivalentIntegerInstanceTwice() {
	Collection<Integer> col = new ArrayList<Integer>(2);
	col.add(new Integer(5));
	col.add(new Integer(5));

	try {
		DataAccessUtils.uniqueResult(col);
		fail("Should have thrown IncorrectResultSizeDataAccessException");
	}
	catch (IncorrectResultSizeDataAccessException ex) {
		// expected
		assertEquals(1, ex.getExpectedSize());
		assertEquals(2, ex.getActualSize());
	}
}
 
Example 9
@Override
public List<JobExecution> getJobExecutions(BatchStatus status, int start, int count) {
	if (start <= 0) {
		return getJdbcTemplate().query(byStatusPagingQueryProvider.generateFirstPageQuery(count),
				new JobExecutionRowMapper(), status.name());
	}
	try {
		Long startAfterValue = getJdbcTemplate().queryForObject(
				byStatusPagingQueryProvider.generateJumpToItemQuery(start, count), Long.class, status.name());
		return getJdbcTemplate().query(byStatusPagingQueryProvider.generateRemainingPagesQuery(count),
				new JobExecutionRowMapper(), status.name(), startAfterValue);
	}
	catch (IncorrectResultSizeDataAccessException e) {
		return Collections.emptyList();
	}
}
 
Example 10
@Test(expected = IncorrectResultSizeDataAccessException.class)
@SuppressWarnings("serial")
public void testGetAnnotationCollectionByIdTwo() {

    W3CAnnotationCollection w3cAnnotationCollection = generateRandomW3CAnnotationCollection();

    String collectionId = w3cAnnotationCollection.getCollectionId();
    Object[] params = {collectionId, false};
    int[] sqlTypes = {Types.VARCHAR, Types.BOOLEAN};

    when(jdbcTemplate.query(anyString(), aryEq(params), aryEq(sqlTypes), (W3CAnnotationCollectionRowMapper) any())).thenReturn(new ArrayList<W3CAnnotationCollection>() {
        {
            add(w3cAnnotationCollection);
            add(w3cAnnotationCollection);
        }
    });
    annotationCollectionStoreRepository.getAnnotationCollectionById(collectionId);
}
 
Example 11
@SuppressWarnings("serial")
@Test(expected = IncorrectResultSizeDataAccessException.class)
public void testGetAnnotationByCollectionIdAndAnnotationIdTwo() {

    W3CAnnotation w3cAnnotation = generateRandomW3CAnnotation();

    String collectionId = generateRandomId();
    String annotationId = generateRandomId();
    Object[] params = {collectionId, annotationId, false};
    int[] sqlTypes = {Types.VARCHAR, Types.VARCHAR, Types.BOOLEAN};

    when(jdbcTemplate.query(anyString(), aryEq(params), aryEq(sqlTypes), (W3CAnnotationRowMapper) any())).thenReturn(new ArrayList<W3CAnnotation>() {
        {
            add(w3cAnnotation);
            add(w3cAnnotation);
        }
    });
    annotationStoreRepository.getAnnotationByCollectionIdAndAnnotationId(collectionId, annotationId);
}
 
Example 12
/*** QUERY HANDLERS ***/

    @QueryHandler
    @Override
    public Optional<User> onGetUserQuery(GetUserQuery query) {
        if (ldapAuthenticationProvider == null) {
            throw new RuntimeException("This functionality is not available with profile " + NOLDAP);
        }
        UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LdapSearchContext ldapSearchContext = createLdapSearchContext(ldapAuthenticationProvider, auth);
        try {
            Collection<? extends GrantedAuthority> springAuthorities = ldapAuthenticationProvider.loadUserAuthorities(
                    ldapSearchContext.searchUserCNWithRetry(query.getUsername()), auth.getName(), (String) auth.getCredentials());
            return Optional.of(new User(query.getUsername(), springAuthorities));
        } catch (IncorrectResultSizeDataAccessException incorrectResultSizeException) {
            if (incorrectResultSizeException.getActualSize() == 0) {
                return Optional.empty();
            }
            throw incorrectResultSizeException;

        } finally {
            ldapSearchContext.closeContext();
        }
    }
 
Example 13
Source Project: sdn-rx   Source File: ReactiveNeo4jTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return A single result
 * @throws IncorrectResultSizeDataAccessException if there is no or more than one result
 */
public Mono<T> getSingleResult() {
	try {
		return fetchSpec.one();
	} catch (NoSuchRecordException e) {
		// This exception is thrown by the driver in both cases when there are 0 or 1+n records
		// So there has been an incorrect result size, but not to few results but to many.
		throw new IncorrectResultSizeDataAccessException(1);
	}
}
 
Example 14
Source Project: sdn-rx   Source File: Neo4jTemplate.java    License: Apache License 2.0 5 votes vote down vote up
public Optional<T> getSingleResult() {
	try {
		return fetchSpec.one();
	} catch (NoSuchRecordException e) {
		// This exception is thrown by the driver in both cases when there are 0 or 1+n records
		// So there has been an incorrect result size, but not to few results but to many.
		throw new IncorrectResultSizeDataAccessException(1);
	}
}
 
Example 15
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
	EntityNotFoundException entityNotFound = new EntityNotFoundException();
	assertSame(JpaObjectRetrievalFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());

	NoResultException noResult = new NoResultException();
	assertSame(EmptyResultDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());

	NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
	assertSame(IncorrectResultSizeDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());

	OptimisticLockException optimisticLock = new OptimisticLockException();
	assertSame(JpaOptimisticLockingFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());

	EntityExistsException entityExists = new EntityExistsException("foo");
	assertSame(DataIntegrityViolationException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());

	TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
	assertSame(InvalidDataAccessApiUsageException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());

	PersistenceException unknown = new PersistenceException() {
	};
	assertSame(JpaSystemException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
 
Example 16
Source Project: spring-analysis-note   Source File: DataAccessUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Return a single result object from the given Collection.
 * <p>Returns {@code null} if 0 result objects found;
 * throws an exception if more than 1 element found.
 * @param results the result Collection (can be {@code null})
 * @return the single result object, or {@code null} if none
 * @throws IncorrectResultSizeDataAccessException if more than one
 * element has been found in the given Collection
 */
@Nullable
public static <T> T singleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
	if (CollectionUtils.isEmpty(results)) {
		return null;
	}
	if (results.size() > 1) {
		throw new IncorrectResultSizeDataAccessException(1, results.size());
	}
	return results.iterator().next();
}
 
Example 17
Source Project: spring-analysis-note   Source File: DataAccessUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Return a single result object from the given Collection.
 * <p>Throws an exception if 0 or more than 1 element found.
 * @param results the result Collection (can be {@code null}
 * and is also expected to contain {@code null} elements)
 * @return the single result object
 * @throws IncorrectResultSizeDataAccessException if more than one
 * element has been found in the given Collection
 * @throws EmptyResultDataAccessException if no element at all
 * has been found in the given Collection
 * @since 5.0.2
 */
@Nullable
public static <T> T nullableSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
	// This is identical to the requiredSingleResult implementation but differs in the
	// semantics of the incoming Collection (which we currently can't formally express)
	if (CollectionUtils.isEmpty(results)) {
		throw new EmptyResultDataAccessException(1);
	}
	if (results.size() > 1) {
		throw new IncorrectResultSizeDataAccessException(1, results.size());
	}
	return results.iterator().next();
}
 
Example 18
Source Project: spring-analysis-note   Source File: SqlQueryTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testFindTooManyCustomers() throws SQLException {
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getInt("id")).willReturn(1, 2);
	given(resultSet.getString("forename")).willReturn("rod", "rod");

	class CustomerQuery extends MappingSqlQuery<Customer> {

		public CustomerQuery(DataSource ds) {
			super(ds, SELECT_ID_FORENAME_WHERE);
			declareParameter(new SqlParameter(Types.VARCHAR));
			compile();
		}

		@Override
		protected Customer mapRow(ResultSet rs, int rownum) throws SQLException {
			Customer cust = new Customer();
			cust.setId(rs.getInt(COLUMN_NAMES[0]));
			cust.setForename(rs.getString(COLUMN_NAMES[1]));
			return cust;
		}

		public Customer findCustomer(String id) {
			return findObject(id);
		}
	}

	CustomerQuery query = new CustomerQuery(dataSource);
	assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() ->
			query.findCustomer("rod"));
	verify(preparedStatement).setString(1, "rod");
	verify(connection).prepareStatement(SELECT_ID_FORENAME_WHERE);
	verify(resultSet).close();
	verify(preparedStatement).close();
	verify(connection).close();
}
 
Example 19
Source Project: spring-analysis-note   Source File: JdbcTemplateQueryTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testQueryForObjectThrowsIncorrectResultSizeForMoreThanOneRow() throws Exception {
	String sql = "select pass from t_account where first_name='Alef'";
	given(this.resultSet.next()).willReturn(true, true, false);
	given(this.resultSet.getString(1)).willReturn("pass");
	assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() ->
			this.template.queryForObject(sql, String.class));
	verify(this.resultSet).close();
	verify(this.statement).close();
}
 
Example 20
Source Project: spring-analysis-note   Source File: LobSupportTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testAbstractLobStreamingResultSetExtractorNoRows() throws SQLException {
	ResultSet rset = mock(ResultSet.class);
	AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
	assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() ->
			lobRse.extractData(rset));
	verify(rset).next();
}
 
Example 21
Source Project: spring-analysis-note   Source File: LobSupportTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testAbstractLobStreamingResultSetExtractorMultipleRows()
		throws SQLException {
	ResultSet rset = mock(ResultSet.class);
	given(rset.next()).willReturn(true, true, false);
	AbstractLobStreamingResultSetExtractor<Void> lobRse = getResultSetExtractor(false);
	assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() ->
			lobRse.extractData(rset));
	verify(rset).clearWarnings();
}
 
Example 22
@Override
protected void processGetOperation(ActionOperationActivateDoubleOptInParameters operation) {
	List<Map<String, Object>> result = select(logger, "SELECT for_all_lists, media_type FROM actop_activate_doi_tbl WHERE action_operation_id = ?", operation.getId());
	if (result.size() == 0) {
		operation.setForAllLists(false);
		processSaveOperation(operation);
	} else if (result.size() == 1) {
		final Map<String, Object> map = result.get(0);
		operation.setForAllLists(((Number) map.get("for_all_lists")).intValue() != 0);
		operation.setMediaType(extractMediaType(map));
	} else {
		throw new IncorrectResultSizeDataAccessException("Invalid multiple data found in actop_activate_doi_tbl for action_operation_id: " + operation.getId(), 1, result.size());
	}
}
 
Example 23
public List<R> extractData(ResultSet rs) throws SQLException, DataAccessException {
    List<R> results = new ArrayList<R>();
    int row = 0;
    boolean more = rs.next();
    if (more) {
        row++;
    }
    while (more) {
        R root = rootMapper.mapRow(rs, row);
        K primaryKey = mapPrimaryKey(rs);
        if (mapForeignKey(rs) != null) {
            while (more && primaryKey.equals(mapForeignKey(rs))) {
                addChild(root, childMapper.mapRow(rs, row));
                more = rs.next();
                if (more) {
                    row++;
                }
            }
        } else {
            more = rs.next();
            if (more) {
                row++;
            }
        }
        results.add(root);
    }
    if ((expectedResults == ExpectedResults.ONE_AND_ONLY_ONE || expectedResults == ExpectedResults.ONE_OR_NONE)
            && results.size() > 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    }
    if ((expectedResults == ExpectedResults.ONE_AND_ONLY_ONE || expectedResults == ExpectedResults.AT_LEAST_ONE)
            && results.size() < 1) {
        throw new IncorrectResultSizeDataAccessException(1, 0);
    }
    return results;
}
 
Example 24
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
	EntityNotFoundException entityNotFound = new EntityNotFoundException();
	assertSame(JpaObjectRetrievalFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());

	NoResultException noResult = new NoResultException();
	assertSame(EmptyResultDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());

	NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
	assertSame(IncorrectResultSizeDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());

	OptimisticLockException optimisticLock = new OptimisticLockException();
	assertSame(JpaOptimisticLockingFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());

	EntityExistsException entityExists = new EntityExistsException("foo");
	assertSame(DataIntegrityViolationException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());

	TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
	assertSame(InvalidDataAccessApiUsageException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());

	PersistenceException unknown = new PersistenceException() {
	};
	assertSame(JpaSystemException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
 
Example 25
Source Project: java-technology-stack   Source File: DataAccessUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Return a single result object from the given Collection.
 * <p>Returns {@code null} if 0 result objects found;
 * throws an exception if more than 1 element found.
 * @param results the result Collection (can be {@code null})
 * @return the single result object, or {@code null} if none
 * @throws IncorrectResultSizeDataAccessException if more than one
 * element has been found in the given Collection
 */
@Nullable
public static <T> T singleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
	if (CollectionUtils.isEmpty(results)) {
		return null;
	}
	if (results.size() > 1) {
		throw new IncorrectResultSizeDataAccessException(1, results.size());
	}
	return results.iterator().next();
}
 
Example 26
Source Project: java-technology-stack   Source File: DataAccessUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Return a single result object from the given Collection.
 * <p>Throws an exception if 0 or more than 1 element found.
 * @param results the result Collection (can be {@code null}
 * and is also expected to contain {@code null} elements)
 * @return the single result object
 * @throws IncorrectResultSizeDataAccessException if more than one
 * element has been found in the given Collection
 * @throws EmptyResultDataAccessException if no element at all
 * has been found in the given Collection
 * @since 5.0.2
 */
@Nullable
public static <T> T nullableSingleResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
	// This is identical to the requiredSingleResult implementation but differs in the
	// semantics of the incoming Collection (which we currently can't formally express)
	if (CollectionUtils.isEmpty(results)) {
		throw new EmptyResultDataAccessException(1);
	}
	if (results.size() > 1) {
		throw new IncorrectResultSizeDataAccessException(1, results.size());
	}
	return results.iterator().next();
}
 
Example 27
Source Project: java-technology-stack   Source File: DataAccessUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Return a unique result object from the given Collection.
 * <p>Returns {@code null} if 0 result objects found;
 * throws an exception if more than 1 instance found.
 * @param results the result Collection (can be {@code null})
 * @return the unique result object, or {@code null} if none
 * @throws IncorrectResultSizeDataAccessException if more than one
 * result object has been found in the given Collection
 * @see org.springframework.util.CollectionUtils#hasUniqueObject
 */
@Nullable
public static <T> T uniqueResult(@Nullable Collection<T> results) throws IncorrectResultSizeDataAccessException {
	if (CollectionUtils.isEmpty(results)) {
		return null;
	}
	if (!CollectionUtils.hasUniqueObject(results)) {
		throw new IncorrectResultSizeDataAccessException(1, results.size());
	}
	return results.iterator().next();
}
 
Example 28
@Override
public List<SchedulerExecution> findAll(final int startIndex, final int pageSize) {
    if (startIndex <= 0) {
        return this.jdbcTemplate.query(this.findAllPagingQueryProvider.generateFirstPageQuery(pageSize),
                this.rowMapper);
    }
    try {
        final Long startAfterValue = this.jdbcTemplate.queryForObject(
                this.findAllPagingQueryProvider.generateJumpToItemQuery(startIndex, pageSize), Long.class);
        return this.jdbcTemplate.query(this.findAllPagingQueryProvider.generateRemainingPagesQuery(pageSize),
                this.rowMapper, startAfterValue);
    } catch (final IncorrectResultSizeDataAccessException e) {
        return Collections.emptyList();
    }
}
 
Example 29
Source Project: java-technology-stack   Source File: SqlQueryTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testFindTooManyCustomers() throws SQLException {
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getInt("id")).willReturn(1, 2);
	given(resultSet.getString("forename")).willReturn("rod", "rod");

	class CustomerQuery extends MappingSqlQuery<Customer> {

		public CustomerQuery(DataSource ds) {
			super(ds, SELECT_ID_FORENAME_WHERE);
			declareParameter(new SqlParameter(Types.VARCHAR));
			compile();
		}

		@Override
		protected Customer mapRow(ResultSet rs, int rownum) throws SQLException {
			Customer cust = new Customer();
			cust.setId(rs.getInt(COLUMN_NAMES[0]));
			cust.setForename(rs.getString(COLUMN_NAMES[1]));
			return cust;
		}

		public Customer findCustomer(String id) {
			return findObject(id);
		}
	}

	CustomerQuery query = new CustomerQuery(dataSource);
	thrown.expect(IncorrectResultSizeDataAccessException.class);
	try {
		query.findCustomer("rod");
	}
	finally {
		verify(preparedStatement).setString(1, "rod");
		verify(connection).prepareStatement(SELECT_ID_FORENAME_WHERE);
		verify(resultSet).close();
		verify(preparedStatement).close();
		verify(connection).close();
	}
}
 
Example 30
Source Project: java-technology-stack   Source File: JdbcTemplateQueryTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testQueryForObjectThrowsIncorrectResultSizeForMoreThanOneRow() throws Exception {
	String sql = "select pass from t_account where first_name='Alef'";
	given(this.resultSet.next()).willReturn(true, true, false);
	given(this.resultSet.getString(1)).willReturn("pass");
	this.thrown.expect(IncorrectResultSizeDataAccessException.class);
	try {
		this.template.queryForObject(sql, String.class);
	}
	finally {
		verify(this.resultSet).close();
		verify(this.statement).close();
	}
}