org.springframework.dao.IncorrectResultSizeDataAccessException Java Examples

The following examples show how to use org.springframework.dao.IncorrectResultSizeDataAccessException. 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 File: DataAccessUtils.java    From lams with 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 #2
Source File: DataAccessUtilsTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: JdbcSearchableJobExecutionDao.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #4
Source File: JdbcSearchableJobExecutionDao.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: DataAccessUtils.java    From java-technology-stack with 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 #6
Source File: DataAccessUtilsTests.java    From spring-analysis-note with 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 #7
Source File: DataAccessUtils.java    From spring-analysis-note with 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 #8
Source File: AnnotationCollectionStoreRepositoryJDBCImplTest.java    From elucidate-server with MIT License 6 votes vote down vote up
@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 #9
Source File: AnnotationStoreRepositoryJDBCImplTest.java    From elucidate-server with MIT License 6 votes vote down vote up
@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 #10
Source File: JdbcSearchableJobExecutionDao.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #11
Source File: JdbcSearchableJobExecutionDao.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #12
Source File: LdapUserRepository.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
/*** 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 File: AnnotationAgentStoreRepositoryJDBCImpl.java    From elucidate-server with MIT License 5 votes vote down vote up
@Override
public AnnotationAgent deleteAnnotationGenerators(Integer annotationPK, Integer bodyPK, Integer targetPK) {
    String sql = "SELECT * FROM annotation_generator_delete(?, ?, ?)";
    Object[] params = {annotationPK, bodyPK, targetPK};
    int[] sqlTypes = {Types.INTEGER, Types.INTEGER, Types.INTEGER};

    List<AnnotationAgent> annotationAgents = queryForObject(sql, params, sqlTypes, new AnnotationAgentResultSetExtractor());
    if (annotationAgents.isEmpty()) {
        return null;
    } else if (annotationAgents.size() == 1) {
        return annotationAgents.get(0);
    } else {
        throw new IncorrectResultSizeDataAccessException(0, annotationAgents.size());
    }
}
 
Example #14
Source File: EntityManagerFactoryUtilsTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #15
Source File: AbstractRepositoryJDBCImpl.java    From elucidate-server with MIT License 5 votes vote down vote up
protected <T> T queryForObject(String sql, Object[] params, int[] sqlTypes, RowMapper<T> rowMapper) {
    List<T> results = queryForList(sql, params, sqlTypes, rowMapper);
    if (results.isEmpty()) {
        return null;
    } else if (results.size() == 1) {
        return results.get(0);
    } else {
        throw new IncorrectResultSizeDataAccessException(0, results.size());
    }
}
 
Example #16
Source File: LdapSearchContext.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
public HashSet<String> retrieveParentGroupDNs(String dn) {
    HashSet<String> parentGroupDNs = new HashSet<>();
    try {
        String cn = DirectoryGroupDN.extractCnFromDn(dn);
        String base = getBaseFrom(cn, dn);
        String searchFilter = ldapConfiguration.getSearchFilterForCN(cn);
        DirContextOperations dirContextOperations = searchCNWithRetry(cn, base, searchFilter);
        parentGroupDNs = extractDirectParentGroupDNs(dirContextOperations.getAttributes(""));
    } catch (IncorrectResultSizeDataAccessException e) {
        // On accepte que la recherche ne retourne aucun résultat
    } catch (NamingException exception) {
        throw LdapUtils.convertLdapException(exception);
    }
    return parentGroupDNs;
}
 
Example #17
Source File: LdapUserRepository.java    From hesperides with GNU General Public License v3.0 5 votes vote down vote up
@QueryHandler
@Override
public DirectoryGroupsView onResolveDirectoryGroupCNsQuery(ResolveDirectoryGroupCNsQuery query) {
    if (ldapAuthenticationProvider == null) {
        return DirectoryGroupsView.allUnresolved(query.getDirectoryGroupCNs());
    }
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
    LdapSearchContext ldapSearchContext = createLdapSearchContext(ldapAuthenticationProvider, auth);
    try {
        List<String> unresolvedDirectoryGroupCNs = new ArrayList<>();
        List<String> ambiguousDirectoryGroupCNs = new ArrayList<>();
        List<String> directoryGroupDNs = new ArrayList<>();

        query.getDirectoryGroupCNs().stream().forEach(groupCN -> {
            // On doit bénéficier du cache durant cet appel :
            try {
                DirContextOperations dirContextOperations = ldapSearchContext.searchUserCNWithRetry(groupCN);
                directoryGroupDNs.add(dirContextOperations.getNameInNamespace());
            } catch (IncorrectResultSizeDataAccessException incorrectResultSizeException) {
                if (incorrectResultSizeException.getActualSize() == 0) {
                    unresolvedDirectoryGroupCNs.add(groupCN);
                } else if (incorrectResultSizeException.getActualSize() > 1) {
                    ambiguousDirectoryGroupCNs.add(groupCN);
                }
            }
        });
        return new DirectoryGroupsView(unresolvedDirectoryGroupCNs, ambiguousDirectoryGroupCNs, directoryGroupDNs);
    } finally {
        ldapSearchContext.closeContext();
    }
}
 
Example #18
Source File: QueryDatabaseAuthenticationHandler.java    From web-sso with Apache License 2.0 5 votes vote down vote up
protected final boolean authenticateUsernamePasswordInternal(final UsernamePasswordCredential credentials) throws AuthenticationException {
    final String username = credentials.getUsername();
    final String password = credentials.getPassword();
    final String encryptedPassword = this.getPasswordEncoder().encode(
        password);
    
    try {
        final String dbPassword = getJdbcTemplate().queryForObject(this.sql, String.class, username);
        return dbPassword.equals(encryptedPassword);
    } catch (final IncorrectResultSizeDataAccessException e) {
        // this means the username was not found.
        return false;
    }
}
 
Example #19
Source File: AnnotationAgentStoreRepositoryJDBCImpl.java    From elucidate-server with MIT License 5 votes vote down vote up
@Override
public AnnotationAgent deleteAnnotationCreators(Integer annotationPK, Integer bodyPK, Integer targetPK) {
    String sql = "SELECT * FROM annotation_creator_delete(?, ?, ?)";
    Object[] params = {annotationPK, bodyPK, targetPK};
    int[] sqlTypes = {Types.INTEGER, Types.INTEGER, Types.INTEGER};

    List<AnnotationAgent> annotationAgents = queryForObject(sql, params, sqlTypes, new AnnotationAgentResultSetExtractor());
    if (annotationAgents.isEmpty()) {
        return null;
    } else if (annotationAgents.size() == 1) {
        return annotationAgents.get(0);
    } else {
        throw new IncorrectResultSizeDataAccessException(0, annotationAgents.size());
    }
}
 
Example #20
Source File: AnnotationAgentStoreRepositoryJDBCImpl.java    From elucidate-server with MIT License 5 votes vote down vote up
@Override
public AnnotationAgent createAnnotationGenerator(Integer annotationPK, Integer bodyPK, Integer targetPK, String generatorIri, String generatorJson, String[] types, String[] typesJson, String[] names, String[] namesJson, String nickname, String[] emails, String[] emailsJson, String[] emailSha1s, String[] emailSha1sJson, String[] homepages, String[] homepagesJson) {
    String sql = "SELECT * FROM annotation_generator_create(?, ?, ?, ?, ?, string_to_array(?, ','), string_to_array(?, ',')::jsonb[], string_to_array(?, ','), string_to_array(?, ',')::jsonb[], ?, string_to_array(?, ','), string_to_array(?, ',')::jsonb[], string_to_array(?, ','), string_to_array(?, ',')::jsonb[], string_to_array(?, ','), string_to_array(?, ',')::jsonb[])";
    Object[] params = {annotationPK, bodyPK, targetPK, generatorIri, generatorJson, String.join(",", types), String.join(",", typesJson), String.join(",", names), String.join(",", namesJson), nickname, String.join(",", emails), String.join(",", emailsJson), String.join(",", emailSha1s), String.join(",", emailSha1sJson), String.join(",", homepages), String.join(",", homepagesJson)};
    int[] sqlTypes = {Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR, Types.OTHER, Types.VARCHAR, Types.OTHER, Types.VARCHAR, Types.OTHER, Types.VARCHAR, Types.VARCHAR, Types.OTHER, Types.VARCHAR, Types.OTHER, Types.VARCHAR, Types.OTHER};

    List<AnnotationAgent> annotationAgents = queryForObject(sql, params, sqlTypes, new AnnotationAgentResultSetExtractor());
    if (annotationAgents.isEmpty()) {
        return null;
    } else if (annotationAgents.size() == 1) {
        return annotationAgents.get(0);
    } else {
        throw new IncorrectResultSizeDataAccessException(0, annotationAgents.size());
    }
}
 
Example #21
Source File: PortalPersonDirUserPasswordDaoTest.java    From uPortal-start with Apache License 2.0 5 votes vote down vote up
public void testDuplicateUser() {
    this.jdbcTemplate.update("INSERT INTO UP_PERSON_DIR VALUES ('foobar', 'pass1')");
    this.jdbcTemplate.update("INSERT INTO UP_PERSON_DIR VALUES ('foobar', 'pass2')");

    try {
        this.userPasswordDao.getPasswordHash("foobar");
        fail("should have thrown IncorrectResultSizeDataAccessException");
    } catch (IncorrectResultSizeDataAccessException e) {
        //expected
    }
}
 
Example #22
Source File: DataAccessUtils.java    From spring4-understanding with Apache License 2.0 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
 */
public static <T> T uniqueResult(Collection<T> results) throws IncorrectResultSizeDataAccessException {
	int size = (results != null ? results.size() : 0);
	if (size == 0) {
		return null;
	}
	if (!CollectionUtils.hasUniqueObject(results)) {
		throw new IncorrectResultSizeDataAccessException(1, size);
	}
	return results.iterator().next();
}
 
Example #23
Source File: DataAccessUtils.java    From spring4-understanding with Apache License 2.0 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})
 * @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
 */
public static <T> T requiredSingleResult(Collection<T> results) throws IncorrectResultSizeDataAccessException {
	int size = (results != null ? results.size() : 0);
	if (size == 0) {
		throw new EmptyResultDataAccessException(1);
	}
	if (results.size() > 1) {
		throw new IncorrectResultSizeDataAccessException(1, size);
	}
	return results.iterator().next();
}
 
Example #24
Source File: DataAccessUtils.java    From spring4-understanding with Apache License 2.0 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
 */
public static <T> T singleResult(Collection<T> results) throws IncorrectResultSizeDataAccessException {
	int size = (results != null ? results.size() : 0);
	if (size == 0) {
		return null;
	}
	if (results.size() > 1) {
		throw new IncorrectResultSizeDataAccessException(1, size);
	}
	return results.iterator().next();
}
 
Example #25
Source File: JdbcTemplateQueryTests.java    From spring4-understanding with Apache License 2.0 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();
	}
}
 
Example #26
Source File: MultiDeviceTokenRepository.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
/**
 * トークンを取得します。
 * 
 * @param series
 * @return
 */
public MultiDeviceRememberMeToken getTokenForSeries(String series) {
    MultiDeviceRememberMeToken token = null;

    try {
        token = getJdbcTemplate().queryForObject(tokensBySeriesSql, (rs, rowNum) -> {
            val t = new MultiDeviceRememberMeToken();
            t.setUsername(rs.getString(1));
            t.setRemoteAddress(rs.getString(2));
            t.setUserAgent(rs.getString(3));
            t.setSeries(rs.getString(4));
            t.setTokenValue(rs.getString(5));
            t.setLastUsed(rs.getTimestamp(6).toLocalDateTime());
            return t;
        }, series);
    } catch (EmptyResultDataAccessException zeroResults) {
        if (log.isDebugEnabled()) {
            log.debug("Querying token for series '{}' returned no results.", series, zeroResults);
        }
    } catch (IncorrectResultSizeDataAccessException moreThanOne) {
        log.error("Querying token for series '{}' returned more than one value. Series should be unique", series);
    } catch (DataAccessException e) {
        log.error("Failed to load token for series {}", series, e);
    }

    return token;
}
 
Example #27
Source File: JdbcLightminJobExecutionDao.java    From spring-batch-lightmin with Apache License 2.0 5 votes vote down vote up
@Override
public List<JobExecution> getJobExecutions(final String jobName, final int start, final int count) {
    if (start <= 0) {
        return this.getJdbcTemplate().query(this.byJobNamePagingQueryProvider.generateFirstPageQuery(count),
                new JobExecutionRowMapper(), jobName);
    }
    try {
        final Long startAfterValue = this.getJdbcTemplate().queryForObject(
                this.byJobNamePagingQueryProvider.generateJumpToItemQuery(start, count), Long.class, jobName);
        return this.getJdbcTemplate().query(this.byJobNamePagingQueryProvider.generateRemainingPagesQuery(count),
                new JobExecutionRowMapper(), jobName, startAfterValue);
    } catch (final IncorrectResultSizeDataAccessException e) {
        return Collections.emptyList();
    }
}
 
Example #28
Source File: DataAccessUtils.java    From lams with GNU General Public License v2.0 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
 */
public static <T> T uniqueResult(Collection<T> results) throws IncorrectResultSizeDataAccessException {
	int size = (results != null ? results.size() : 0);
	if (size == 0) {
		return null;
	}
	if (!CollectionUtils.hasUniqueObject(results)) {
		throw new IncorrectResultSizeDataAccessException(1, size);
	}
	return results.iterator().next();
}
 
Example #29
Source File: ReactiveNeo4jTemplate.java    From sdn-rx with 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 #30
Source File: SimpleQuerydslJdbcRepository.java    From infobip-spring-data-querydsl with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<T> findOne(Predicate predicate) {
    try {
        return Optional.ofNullable(sqlQueryFactory.query()
                                                  .select(entityProjection())
                                                  .where(predicate)
                                                  .from(path)
                                                  .fetchOne());
    } catch (NonUniqueResultException ex) {
        throw new IncorrectResultSizeDataAccessException(ex.getMessage(), 1, ex);
    }
}