org.springframework.dao.InvalidDataAccessApiUsageException Java Examples

The following examples show how to use org.springframework.dao.InvalidDataAccessApiUsageException. 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: JdbcTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testExecuteClosed() throws Exception {
	given(this.resultSet.next()).willReturn(true);
	given(this.callableStatement.execute()).willReturn(true);
	given(this.callableStatement.getUpdateCount()).willReturn(-1);

	SqlParameter param = new SqlReturnResultSet("", (RowCallbackHandler) rs -> {
		throw new InvalidDataAccessApiUsageException("");
	});

	this.thrown.expect(InvalidDataAccessApiUsageException.class);
	try {
		this.template.call(conn -> conn.prepareCall("my query"), Collections.singletonList(param));
	}
	finally {
		verify(this.resultSet).close();
		verify(this.callableStatement).close();
		verify(this.connection).close();
	}
}
 
Example #2
Source File: ReactiveNeo4jQueryMethod.java    From sdn-rx with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new {@link ReactiveNeo4jQueryMethod} from the given parameters.
 *
 * @param method   must not be {@literal null}.
 * @param metadata must not be {@literal null}.
 * @param factory  must not be {@literal null}.
 */
ReactiveNeo4jQueryMethod(Method method, RepositoryMetadata metadata, ProjectionFactory factory) {
	super(method, metadata, factory);

	if (hasParameterOfType(method, Pageable.class)) {

		TypeInformation<?> returnType = ClassTypeInformation.fromReturnTypeOf(method);

		boolean multiWrapper = ReactiveWrappers.isMultiValueType(returnType.getType());
		boolean singleWrapperWithWrappedPageableResult = ReactiveWrappers.isSingleValueType(returnType.getType())
			&& (PAGE_TYPE.isAssignableFrom(returnType.getRequiredComponentType())
			|| SLICE_TYPE.isAssignableFrom(returnType.getRequiredComponentType()));

		if (singleWrapperWithWrappedPageableResult) {
			throw new InvalidDataAccessApiUsageException(
				String.format("'%s.%s' must not use sliced or paged execution. Please use Flux.buffer(size, skip).",
					ClassUtils.getShortName(method.getDeclaringClass()), method.getName()));
		}

		if (!multiWrapper) {
			throw new IllegalStateException(String.format(
				"Method has to use a multi-item reactive wrapper return type. Offending method: %s",
				method.toString()));
		}
	}
}
 
Example #3
Source File: RdbmsOperation.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Validate the named parameters passed to an execute method based on declared parameters.
 * Subclasses should invoke this method before every {@code executeQuery()} or
 * {@code update()} method.
 * @param parameters parameter Map supplied (may be {@code null})
 * @throws InvalidDataAccessApiUsageException if the parameters are invalid
 */
protected void validateNamedParameters(@Nullable Map<String, ?> parameters) throws InvalidDataAccessApiUsageException {
	checkCompiled();
	Map<String, ?> paramsToUse = (parameters != null ? parameters : Collections.<String, Object> emptyMap());
	int declaredInParameters = 0;
	for (SqlParameter param : this.declaredParameters) {
		if (param.isInputValueProvided()) {
			if (!supportsLobParameters() &&
					(param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) {
				throw new InvalidDataAccessApiUsageException(
						"BLOB or CLOB parameters are not allowed for this kind of operation");
			}
			if (param.getName() != null && !paramsToUse.containsKey(param.getName())) {
				throw new InvalidDataAccessApiUsageException("The parameter named '" + param.getName() +
						"' was not among the parameters supplied: " + paramsToUse.keySet());
			}
			declaredInParameters++;
		}
	}
	validateParameterCount(paramsToUse.size(), declaredInParameters);
}
 
Example #4
Source File: RdbmsOperation.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Validate the parameters passed to an execute method based on declared parameters.
 * Subclasses should invoke this method before every {@code executeQuery()}
 * or {@code update()} method.
 * @param parameters parameters supplied (may be {@code null})
 * @throws InvalidDataAccessApiUsageException if the parameters are invalid
 */
protected void validateParameters(@Nullable Object[] parameters) throws InvalidDataAccessApiUsageException {
	checkCompiled();
	int declaredInParameters = 0;
	for (SqlParameter param : this.declaredParameters) {
		if (param.isInputValueProvided()) {
			if (!supportsLobParameters() &&
					(param.getSqlType() == Types.BLOB || param.getSqlType() == Types.CLOB)) {
				throw new InvalidDataAccessApiUsageException(
						"BLOB or CLOB parameters are not allowed for this kind of operation");
			}
			declaredInParameters++;
		}
	}
	validateParameterCount((parameters != null ? parameters.length : 0), declaredInParameters);
}
 
Example #5
Source File: CallMetaDataContext.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a ReturnResultSetParameter/SqlOutParameter depending on the support provided
 * by the JDBC driver used for the database in use.
 * @param parameterName the name of the parameter (also used as the name of the List returned in the output)
 * @param rowMapper a RowMapper implementation used to map the data returned in the result set
 * @return the appropriate SqlParameter
 */
public SqlParameter createReturnResultSetParameter(String parameterName, RowMapper<?> rowMapper) {
	CallMetaDataProvider provider = obtainMetaDataProvider();
	if (provider.isReturnResultSetSupported()) {
		return new SqlReturnResultSet(parameterName, rowMapper);
	}
	else {
		if (provider.isRefCursorSupported()) {
			return new SqlOutParameter(parameterName, provider.getRefCursorSqlType(), rowMapper);
		}
		else {
			throw new InvalidDataAccessApiUsageException(
					"Return of a ResultSet from a stored procedure is not supported");
		}
	}
}
 
Example #6
Source File: SqlQueryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testQueryWithMissingMapParams() {
	MappingSqlQuery<Integer> query = new MappingSqlQuery<Integer>() {
		@Override
		protected Integer mapRow(ResultSet rs, int rownum) throws SQLException {
			return rs.getInt(1);
		}
	};
	query.setDataSource(dataSource);
	query.setSql(SELECT_ID_WHERE);
	query.declareParameter(new SqlParameter(COLUMN_NAMES[0], COLUMN_TYPES[0]));
	query.declareParameter(new SqlParameter(COLUMN_NAMES[1], COLUMN_TYPES[1]));
	query.compile();

	thrown.expect(InvalidDataAccessApiUsageException.class);
	query.executeByNamedParam(Collections.singletonMap(COLUMN_NAMES[0], "value"));
}
 
Example #7
Source File: AbstractJdbcCall.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Compile this JdbcCall using provided parameters and meta-data plus other settings.
 * <p>This finalizes the configuration for this object and subsequent attempts to compile are
 * ignored. This will be implicitly called the first time an un-compiled call is executed.
 * @throws org.springframework.dao.InvalidDataAccessApiUsageException if the object hasn't
 * been correctly initialized, for example if no DataSource has been provided
 */
public final synchronized void compile() throws InvalidDataAccessApiUsageException {
	if (!isCompiled()) {
		if (getProcedureName() == null) {
			throw new InvalidDataAccessApiUsageException("Procedure or Function name is required");
		}
		try {
			this.jdbcTemplate.afterPropertiesSet();
		}
		catch (IllegalArgumentException ex) {
			throw new InvalidDataAccessApiUsageException(ex.getMessage());
		}
		compileInternal();
		this.compiled = true;
		if (logger.isDebugEnabled()) {
			logger.debug("SqlCall for " + (isFunction() ? "function" : "procedure") +
					" [" + getProcedureName() + "] compiled");
		}
	}
}
 
Example #8
Source File: SqlQueryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testQueryWithoutEnoughParams() {
	MappingSqlQuery<Integer> query = new MappingSqlQuery<Integer>() {
		@Override
		protected Integer mapRow(ResultSet rs, int rownum) throws SQLException {
			return rs.getInt(1);
		}
	};
	query.setDataSource(dataSource);
	query.setSql(SELECT_ID_WHERE);
	query.declareParameter(new SqlParameter(COLUMN_NAMES[0], COLUMN_TYPES[0]));
	query.declareParameter(new SqlParameter(COLUMN_NAMES[1], COLUMN_TYPES[1]));
	query.compile();

	thrown.expect(InvalidDataAccessApiUsageException.class);
	query.execute();
}
 
Example #9
Source File: SqlQueryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testQueryWithMissingMapParams() {
	MappingSqlQuery<Integer> query = new MappingSqlQuery<Integer>() {
		@Override
		protected Integer mapRow(ResultSet rs, int rownum) throws SQLException {
			return rs.getInt(1);
		}
	};
	query.setDataSource(dataSource);
	query.setSql(SELECT_ID_WHERE);
	query.declareParameter(new SqlParameter(COLUMN_NAMES[0], COLUMN_TYPES[0]));
	query.declareParameter(new SqlParameter(COLUMN_NAMES[1], COLUMN_TYPES[1]));
	query.compile();

	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			query.executeByNamedParam(Collections.singletonMap(COLUMN_NAMES[0], "value")));
}
 
Example #10
Source File: JdbcTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testBatchUpdateWithNoBatchSupportAndSelect() throws Exception {
	final String[] sql = {"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 1",
			"SELECT * FROM NOSUCHTABLE"};

	given(this.statement.execute(sql[0])).willReturn(false);
	given(this.statement.getUpdateCount()).willReturn(1);
	given(this.statement.execute(sql[1])).willReturn(true);
	mockDatabaseMetaData(false);
	given(this.connection.createStatement()).willReturn(this.statement);

	JdbcTemplate template = new JdbcTemplate(this.dataSource, false);
	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			template.batchUpdate(sql));
	verify(this.statement, never()).addBatch(anyString());
	verify(this.statement).close();
	verify(this.connection, atLeastOnce()).close();
}
 
Example #11
Source File: JdbcTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testStaticResultSetClosed() throws Exception {
	ResultSet resultSet2 = mock(ResultSet.class);
	reset(this.preparedStatement);
	given(this.preparedStatement.executeQuery()).willReturn(resultSet2);
	given(this.connection.createStatement()).willReturn(this.statement);

	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			this.template.query("my query", (ResultSetExtractor<Object>) rs -> {
				throw new InvalidDataAccessApiUsageException("");
			}));
	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			this.template.query(con -> con.prepareStatement("my query"), (ResultSetExtractor<Object>) rs2 -> {
				throw new InvalidDataAccessApiUsageException("");
			}));

	verify(this.resultSet).close();
	verify(resultSet2).close();
	verify(this.preparedStatement).close();
	verify(this.connection, atLeastOnce()).close();
}
 
Example #12
Source File: RegionStatusDaoTest.java    From kardio with Apache License 2.0 5 votes vote down vote up
@Test(expected = InvalidDataAccessApiUsageException.class)
public void testLoadMessages_Invalid() throws ParseException, InstantiationException {
    String environmentName = "envloadmsginvalid";
    String messageType = "INVALID";
    String message = "message_1";
    DaillyCompStatusEntity dcse = daoService.createDailyStatusEntity(environmentName);
    rgDao.loadMessages(environmentName, messageType, message);
}
 
Example #13
Source File: PreparedStatementCreatorImpl.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setValues(PreparedStatement ps) throws SQLException {
    // Set arguments: Does nothing if there are no parameters.
    int sqlColIndx = 1;
    for (int i = 0; i < this.parameters.size(); i++) {
        Object in = this.parameters.get(i);
        SqlParameter declaredParameter;
        // SqlParameterValue overrides declared parameter meta-data, in particular for
        // independence from the declared parameter position in case of named parameters.
        if (in instanceof SqlParameterValue) {
            SqlParameterValue paramValue = (SqlParameterValue) in;
            in = paramValue.getValue();
            declaredParameter = paramValue;
        } else {
            if (declaredParameters.size() <= i) {
                throw new InvalidDataAccessApiUsageException(
                        "SQL [" + actualSql + "]: unable to access parameter number " + (i + 1) +
                                " given only " + declaredParameters.size() + " parameters");

            }
            declaredParameter = declaredParameters.get(i);
        }
        if (in instanceof Iterable && declaredParameter.getSqlType() != Types.ARRAY) {
            Iterable<?> entries = (Iterable<?>) in;
            for (Object entry : entries) {
                if (entry instanceof Object[]) {
                    Object[] valueArray = (Object[]) entry;
                    for (Object argValue : valueArray) {
                        StatementCreatorUtils.setParameterValue(ps, sqlColIndx++, declaredParameter, argValue);
                    }
                } else {
                    StatementCreatorUtils.setParameterValue(ps, sqlColIndx++, declaredParameter, entry);
                }
            }
        } else {
            StatementCreatorUtils.setParameterValue(ps, sqlColIndx++, declaredParameter, in);
        }
    }
}
 
Example #14
Source File: PreparedStatementCreatorImpl.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
private List<Pair<SqlParameter, Object>> flatParameters() {
    final List<Pair<SqlParameter, Object>> ret = Collects.emptyArrayList();
    Collects.forEach(this.parameters, new Consumer2<Integer, Object>() {
        @Override
        public void accept(Integer i, Object in) {
            SqlParameter declaredParameter;
            // SqlParameterValue overrides declared parameter meta-data, in particular for
            // independence from the declared parameter position in case of named parameters.
            if (in instanceof SqlParameterValue) {
                SqlParameterValue paramValue = (SqlParameterValue) in;
                in = paramValue.getValue();
                declaredParameter = paramValue;
            } else {
                if (declaredParameters.size() <= i) {
                    throw new InvalidDataAccessApiUsageException(
                            "SQL [" + getSql() + "]: unable to access parameter number " + (i + 1) +
                                    " given only " + declaredParameters.size() + " parameters");

                }
                declaredParameter = declaredParameters.get(i);
            }
            if (in instanceof Collection && declaredParameter.getSqlType() != Types.ARRAY) {
                Collection<?> entries = (Collection<?>) in;
                for (Object entry : entries) {
                    if (entry instanceof Object[]) {
                        Object[] valueArray = ((Object[]) entry);
                        for (Object argValue : valueArray) {
                            ret.add(new Entry<SqlParameter, Object>(declaredParameter, argValue));
                        }
                    } else {
                        ret.add(new Entry<SqlParameter, Object>(declaredParameter, entry));
                    }
                }
            } else {
                ret.add(new Entry<SqlParameter, Object>(declaredParameter, in));
            }
        }
    });
    return ret;
}
 
Example #15
Source File: NamedParameterPreparedStatementCreator.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
private List<Pair<SqlParameter, Object>> flatParameters() {
    final List<Pair<SqlParameter, Object>> ret = Collects.emptyArrayList();
    Collects.forEach(this.parameters, new Consumer2<Integer, Object>() {
        @Override
        public void accept(Integer i, Object in) {
            SqlParameter declaredParameter;
            // SqlParameterValue overrides declared parameter meta-data, in particular for
            // independence from the declared parameter position in case of named parameters.
            if (in instanceof SqlParameterValue) {
                SqlParameterValue paramValue = (SqlParameterValue) in;
                in = paramValue.getValue();
                declaredParameter = paramValue;
            } else {
                if (factory.getDeclaredParameters().size() <= i) {
                    throw new InvalidDataAccessApiUsageException(
                            "SQL [" + getSql() + "]: unable to access parameter number " + (i + 1) +
                                    " given only " + factory.getDeclaredParameters().size() + " parameters");

                }
                declaredParameter = factory.getDeclaredParameters().get(i);
            }
            if (in instanceof Collection && declaredParameter.getSqlType() != Types.ARRAY) {
                Collection<?> entries = (Collection<?>) in;
                for (Object entry : entries) {
                    if (entry instanceof Object[]) {
                        Object[] valueArray = ((Object[]) entry);
                        for (Object argValue : valueArray) {
                            ret.add(new Entry<SqlParameter, Object>(declaredParameter, argValue));
                        }
                    } else {
                        ret.add(new Entry<SqlParameter, Object>(declaredParameter, entry));
                    }
                }
            } else {
                ret.add(new Entry<SqlParameter, Object>(declaredParameter, in));
            }
        }
    });
    return ret;
}
 
Example #16
Source File: NamedParameterPreparedStatementCreator.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setValues(PreparedStatement ps) throws SQLException {
    // Set arguments: Does nothing if there are no parameters.
    int sqlColIndx = 1;
    for (int i = 0; i < this.parameters.size(); i++) {
        Object in = this.parameters.get(i);
        SqlParameter declaredParameter;
        // SqlParameterValue overrides declared parameter meta-data, in particular for
        // independence from the declared parameter position in case of named parameters.
        if (in instanceof SqlParameterValue) {
            SqlParameterValue paramValue = (SqlParameterValue) in;
            in = paramValue.getValue();
            declaredParameter = paramValue;
        } else {
            if (factory.getDeclaredParameters().size() <= i) {
                throw new InvalidDataAccessApiUsageException(
                        "SQL [" + getSql() + "]: unable to access parameter number " + (i + 1) +
                                " given only " + factory.getDeclaredParameters().size() + " parameters");

            }
            declaredParameter = factory.getDeclaredParameters().get(i);
        }
        if (in instanceof Collection && declaredParameter.getSqlType() != Types.ARRAY) {
            Collection<?> entries = (Collection<?>) in;
            for (Object entry : entries) {
                if (entry instanceof Object[]) {
                    Object[] valueArray = ((Object[]) entry);
                    for (Object argValue : valueArray) {
                        StatementCreatorUtils.setParameterValue(ps, sqlColIndx++, declaredParameter, argValue);
                    }
                } else {
                    StatementCreatorUtils.setParameterValue(ps, sqlColIndx++, declaredParameter, entry);
                }
            }
        } else {
            StatementCreatorUtils.setParameterValue(ps, sqlColIndx++, declaredParameter, in);
        }
    }
}
 
Example #17
Source File: ArgumentTypePreparedStatementSetter.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create a new ArgTypePreparedStatementSetter for the given arguments.
 *
 * @param args     the arguments to set
 * @param argTypes the corresponding SQL types of the arguments
 */
public ArgumentTypePreparedStatementSetter(@Nullable Object[] args, @Nullable int[] argTypes) {
    boolean argsIsNull = args == null;
    boolean argTypesIsNull = argTypes == null;
    if ((argsIsNull != argTypesIsNull) || (!argsIsNull && args.length != argTypes.length)) {
        throw new InvalidDataAccessApiUsageException("args and argTypes parameters must match");
    }

    this.args = args;
    this.argTypes = argTypes;
}
 
Example #18
Source File: Neo4jPersistenceExceptionTranslator.java    From sdn-rx with Apache License 2.0 5 votes vote down vote up
@Override
public DataAccessException translateExceptionIfPossible(RuntimeException ex) {

	if (ex instanceof DataAccessException) {
		return (DataAccessException) ex;
	} else if (ex instanceof DiscoveryException) {
		return translateImpl((Neo4jException) ex, TransientDataAccessResourceException::new);
	} else if (ex instanceof DatabaseException) {
		return translateImpl((Neo4jException) ex, NonTransientDataAccessResourceException::new);
	} else if (ex instanceof ServiceUnavailableException) {
		return translateImpl((Neo4jException) ex, NonTransientDataAccessResourceException::new);
	} else if (ex instanceof SessionExpiredException) {
		return translateImpl((Neo4jException) ex, RecoverableDataAccessException::new);
	} else if (ex instanceof ProtocolException) {
		return translateImpl((Neo4jException) ex, NonTransientDataAccessResourceException::new);
	} else if (ex instanceof TransientException) {
		return translateImpl((Neo4jException) ex, TransientDataAccessResourceException::new);
	} else if (ex instanceof ValueException) {
		return translateImpl((Neo4jException) ex, InvalidDataAccessApiUsageException::new);
	} else if (ex instanceof AuthenticationException) {
		return translateImpl((Neo4jException) ex, PermissionDeniedDataAccessException::new);
	} else if (ex instanceof ResultConsumedException) {
		return translateImpl((Neo4jException) ex, InvalidDataAccessApiUsageException::new);
	} else if (ex instanceof FatalDiscoveryException) {
		return translateImpl((Neo4jException) ex, NonTransientDataAccessResourceException::new);
	} else if (ex instanceof TransactionNestingException) {
		return translateImpl((Neo4jException) ex, InvalidDataAccessApiUsageException::new);
	} else if (ex instanceof ClientException) {
		return translateImpl((Neo4jException) ex, InvalidDataAccessResourceUsageException::new);
	}

	log.warn(() -> String.format("Don't know how to translate exception of type %s", ex.getClass()));
	return null;
}
 
Example #19
Source File: AppFullNameDaoTest.java    From kardio with Apache License 2.0 5 votes vote down vote up
@Test(expected = InvalidDataAccessApiUsageException.class)
@Transactional
@Rollback
public void testUpdateAppFullName_EmptyCompName() {
    AppFullName afn = daoService.getAppFullName();
    afn.setComponentFullName("");
    appFullNameDao.editAppFullName(afn);
}
 
Example #20
Source File: SimpleJdbcCallTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testUnnamedParameterHandling() throws Exception {
	final String MY_PROC = "my_proc";
	SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(MY_PROC);
	// Shouldn't succeed in adding unnamed parameter
	thrown.expect(InvalidDataAccessApiUsageException.class);
	sproc.addDeclaredParameter(new SqlParameter(1));
}
 
Example #21
Source File: BeanPropertyRowMapper.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Set the class that each row should be mapped to.
 */
public void setMappedClass(Class<T> mappedClass) {
	if (this.mappedClass == null) {
		initialize(mappedClass);
	}
	else {
		if (this.mappedClass != mappedClass) {
			throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to " +
					mappedClass + " since it is already providing mapping for " + this.mappedClass);
		}
	}
}
 
Example #22
Source File: RegionMessageDaoTest.java    From kardio with Apache License 2.0 5 votes vote down vote up
@Test(expected = InvalidDataAccessApiUsageException.class)
public void testGetCompRegionMessage_WithDateNullRegtion() throws ParseException {
    Calendar yesterday = Calendar.getInstance();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String startDate = sdf.format(yesterday.getTime());
    regionMessageDao.getCompRegionMessage("envname", "1", null, startDate);
}
 
Example #23
Source File: ChainedPersistenceExceptionTranslatorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void exceptionTranslationWithTranslation() {
	MapPersistenceExceptionTranslator mpet1 = new MapPersistenceExceptionTranslator();
	RuntimeException in1 = new RuntimeException("in");
	InvalidDataAccessApiUsageException out1 = new InvalidDataAccessApiUsageException("out");
	InvalidDataAccessApiUsageException out2 = new InvalidDataAccessApiUsageException("out");
	mpet1.addTranslation(in1, out1);

	ChainedPersistenceExceptionTranslator chainedPet1 = new ChainedPersistenceExceptionTranslator();
	assertSame("Should not translate yet", in1, DataAccessUtils.translateIfNecessary(in1, chainedPet1));
	chainedPet1.addDelegate(mpet1);
	assertSame("Should now translate", out1, DataAccessUtils.translateIfNecessary(in1, chainedPet1));

	// Now add a new translator and verify it wins
	MapPersistenceExceptionTranslator mpet2 = new MapPersistenceExceptionTranslator();
	mpet2.addTranslation(in1, out2);
	chainedPet1.addDelegate(mpet2);
	assertSame("Should still translate the same due to ordering",
			out1, DataAccessUtils.translateIfNecessary(in1, chainedPet1));

	ChainedPersistenceExceptionTranslator chainedPet2 = new ChainedPersistenceExceptionTranslator();
	chainedPet2.addDelegate(mpet2);
	chainedPet2.addDelegate(mpet1);
	assertSame("Should translate differently due to ordering",
			out2, DataAccessUtils.translateIfNecessary(in1, chainedPet2));

	RuntimeException in2 = new RuntimeException("in2");
	OptimisticLockingFailureException out3 = new OptimisticLockingFailureException("out2");
	assertNull(chainedPet2.translateExceptionIfPossible(in2));
	MapPersistenceExceptionTranslator mpet3 = new MapPersistenceExceptionTranslator();
	mpet3.addTranslation(in2, out3);
	chainedPet2.addDelegate(mpet3);
	assertSame(out3, chainedPet2.translateExceptionIfPossible(in2));
}
 
Example #24
Source File: GeneratedKeyHolder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public Number getKey() throws InvalidDataAccessApiUsageException, DataRetrievalFailureException {
	if (this.keyList.isEmpty()) {
		return null;
	}
	if (this.keyList.size() > 1 || this.keyList.get(0).size() > 1) {
		throw new InvalidDataAccessApiUsageException(
				"The getKey method should only be used when a single key is returned.  " +
				"The current key entry contains multiple keys: " + this.keyList);
	}
	Iterator<Object> keyIter = this.keyList.get(0).values().iterator();
	if (keyIter.hasNext()) {
		Object key = keyIter.next();
		if (!(key instanceof Number)) {
			throw new DataRetrievalFailureException(
					"The generated key is not of a supported numeric type. " +
					"Unable to cast [" + (key != null ? key.getClass().getName() : null) +
					"] to [" + Number.class.getName() + "]");
		}
		return (Number) key;
	}
	else {
		throw new DataRetrievalFailureException("Unable to retrieve the generated key. " +
				"Check that the table has an identity column enabled.");
	}
}
 
Example #25
Source File: GeneratedKeyHolder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Nullable
public Map<String, Object> getKeys() throws InvalidDataAccessApiUsageException {
	if (this.keyList.isEmpty()) {
		return null;
	}
	if (this.keyList.size() > 1) {
		throw new InvalidDataAccessApiUsageException(
				"The getKeys method should only be used when keys for a single row are returned.  " +
				"The current key list contains keys for multiple rows: " + this.keyList);
	}
	return this.keyList.get(0);
}
 
Example #26
Source File: KeyHolderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void multipleKeyRows() {
	Map<String, Object> m = new HashMap<String, Object>() {{
		put("key", 1);
		put("seq", 2);
	}};
	kh.getKeyList().addAll(asList(m, m));

	assertEquals("two rows should be in the list", 2, kh.getKeyList().size());
	exception.expect(InvalidDataAccessApiUsageException.class);
	exception.expectMessage(startsWith("The getKeys method should only be used when keys for a single row are returned."));
	kh.getKeys();
}
 
Example #27
Source File: RdbmsOperationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void tooFewMapParameters() {
	operation.setSql("select * from mytable");
	operation.setTypes(new int[] { Types.INTEGER });
	exception.expect(InvalidDataAccessApiUsageException.class);
	operation.validateNamedParameters((Map<String, String>) null);
}
 
Example #28
Source File: EntityManagerFactoryUtilsTests.java    From java-technology-stack with MIT License 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 #29
Source File: RdbmsOperation.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Set whether to use statements that are capable of returning
 * updatable ResultSets.
 * @see java.sql.Connection#prepareStatement(String, int, int)
 */
public void setUpdatableResults(boolean updatableResults) {
	if (isCompiled()) {
		throw new InvalidDataAccessApiUsageException(
				"The updateableResults flag must be set before the operation is compiled");
	}
	this.updatableResults = updatableResults;
}
 
Example #30
Source File: StoredProcedureTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testUnnamedParameter() throws Exception {
	this.verifyClosedAfter = false;
	// Shouldn't succeed in creating stored procedure with unnamed parameter
	thrown.expect(InvalidDataAccessApiUsageException.class);
	new UnnamedParameterStoredProcedure(dataSource);
}