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: 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 #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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
Source File: EntityManagerFactoryUtilsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testTranslatesIllegalStateException() {
	IllegalStateException ise = new IllegalStateException();
	DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ise);
	assertSame(ise, dex.getCause());
	assertTrue(dex instanceof InvalidDataAccessApiUsageException);
}
 
Example #13
Source File: ArgumentTypePreparedStatementSetter.java    From java-technology-stack with MIT License 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) {
	if ((args != null && argTypes == null) || (args == null && argTypes != null) ||
			(args != null && args.length != argTypes.length)) {
		throw new InvalidDataAccessApiUsageException("args and argTypes parameters must match");
	}
	this.args = args;
	this.argTypes = argTypes;
}
 
Example #14
Source File: BeanPropertyRowMapperTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testMappingWithUnpopulatedFieldsNotAccepted() throws Exception {
	Mock mock = new Mock();
	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			mock.getJdbcTemplate().query("select name, age, birth_date, balance from people",
					new BeanPropertyRowMapper<>(ExtendedPerson.class, true)));
}
 
Example #15
Source File: RdbmsOperationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void declareParameterAfterCompile() {
	operation.setDataSource(new DriverManagerDataSource());
	operation.setSql("select * from mytable");
	operation.compile();
	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			operation.declareParameter(new SqlParameter(Types.INTEGER)));
}
 
Example #16
Source File: RdbmsOperationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void unspecifiedMapParameters() {
	operation.setSql("select * from mytable");
	Map<String, String> params = new HashMap<>();
	params.put("col1", "value");
	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			operation.validateNamedParameters(params));
}
 
Example #17
Source File: DataAccessUtilsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void exceptionTranslationWithTranslation() {
	MapPersistenceExceptionTranslator mpet = new MapPersistenceExceptionTranslator();
	RuntimeException in = new RuntimeException("in");
	InvalidDataAccessApiUsageException out = new InvalidDataAccessApiUsageException("out");
	mpet.addTranslation(in, out);
	assertSame(out, DataAccessUtils.translateIfNecessary(in, mpet));
}
 
Example #18
Source File: AlertSubscribeDaoTest.java    From kardio with Apache License 2.0 5 votes vote down vote up
@Test(expected = InvalidDataAccessApiUsageException.class)
@Transactional
@Rollback(true)
public void testCreateAlertSubscribtion_CompIDZero() {
    String envName = "alertsubzerocompid";
    daoService.createEnvironment(envName, 1);
    daoService.createComponentType();
    daoService.createComponent();

    Subscription sub = getSubscription(envName);
    sub.setComponentId(0);

    alertSubscribeDao.saveSubscription(sub, 0, 1, false);
}
 
Example #19
Source File: PersistenceExceptionTranslationAdvisorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected RepositoryInterface createProxy(RepositoryInterfaceImpl target) {
	MapPersistenceExceptionTranslator mpet = new MapPersistenceExceptionTranslator();
	mpet.addTranslation(persistenceException1, new InvalidDataAccessApiUsageException("", persistenceException1));
	ProxyFactory pf = new ProxyFactory(target);
	pf.addInterface(RepositoryInterface.class);
	addPersistenceExceptionTranslation(pf, mpet);
	return (RepositoryInterface) pf.getProxy();
}
 
Example #20
Source File: ArgumentTypePreparedStatementSetter.java    From spring-analysis-note with MIT License 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) {
	if ((args != null && argTypes == null) || (args == null && argTypes != null) ||
			(args != null && args.length != argTypes.length)) {
		throw new InvalidDataAccessApiUsageException("args and argTypes parameters must match");
	}
	this.args = args;
	this.argTypes = argTypes;
}
 
Example #21
Source File: ProcedureParameterUtils.java    From opscenter with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a Map of named parameter values to a corresponding array.
 * @param parsedSqlBean the parsed SQL statement
 * @param paramSource the source for named parameters
 * @param declaredParams the List of declared SqlParameter objects
 * (may be {@code null}). If specified, the parameter metadata will
 * be built into the value array in the form of SqlParameterValue objects.
 * @return the array of values
 */
public static Object[] buildValueArray(
		ParsedSqlBean parsedSqlBean, SqlParameterSource paramSource, @Nullable List<SqlParameter> declaredParams) {

	Object[] paramArray = new Object[parsedSqlBean.getTotalParameterCount()];
	if (parsedSqlBean.getNamedParameterCount() > 0 && parsedSqlBean.getUnnamedParameterCount() > 0) {
		throw new InvalidDataAccessApiUsageException(
				"Not allowed to mix named and traditional ? placeholders. You have " +
				parsedSqlBean.getNamedParameterCount() + " named parameter(s) and " +
				parsedSqlBean.getUnnamedParameterCount() + " traditional placeholder(s) in statement: " +
				parsedSqlBean.getOriginalSql());
	}
	List<String> paramNames = parsedSqlBean.getParameterNames();
	for (int i = 0; i < paramNames.size(); i++) {
		String paramName = paramNames.get(i);
		try {
			Object value = paramSource.getValue(paramName);
			SqlParameter param = findParameter(declaredParams, paramName, i);
			paramArray[i] = (param != null ? new SqlParameterValue(param, value) : value);
		}
		catch (IllegalArgumentException ex) {
			throw new InvalidDataAccessApiUsageException(
					"No value supplied for the SQL parameter '" + paramName + "': " + ex.getMessage());
		}
	}
	return paramArray;
}
 
Example #22
Source File: NamedParameterUtils.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Convert a Map of named parameter values to a corresponding array.
 * @param parsedSql the parsed SQL statement
 * @param paramSource the source for named parameters
 * @param declaredParams the List of declared SqlParameter objects
 * (may be {@code null}). If specified, the parameter metadata will
 * be built into the value array in the form of SqlParameterValue objects.
 * @return the array of values
 */
public static Object[] buildValueArray(
		ParsedSql parsedSql, SqlParameterSource paramSource, @Nullable List<SqlParameter> declaredParams) {

	Object[] paramArray = new Object[parsedSql.getTotalParameterCount()];
	if (parsedSql.getNamedParameterCount() > 0 && parsedSql.getUnnamedParameterCount() > 0) {
		throw new InvalidDataAccessApiUsageException(
				"Not allowed to mix named and traditional ? placeholders. You have " +
				parsedSql.getNamedParameterCount() + " named parameter(s) and " +
				parsedSql.getUnnamedParameterCount() + " traditional placeholder(s) in statement: " +
				parsedSql.getOriginalSql());
	}
	List<String> paramNames = parsedSql.getParameterNames();
	for (int i = 0; i < paramNames.size(); i++) {
		String paramName = paramNames.get(i);
		try {
			Object value = paramSource.getValue(paramName);
			SqlParameter param = findParameter(declaredParams, paramName, i);
			paramArray[i] = (param != null ? new SqlParameterValue(param, value) : value);
		}
		catch (IllegalArgumentException ex) {
			throw new InvalidDataAccessApiUsageException(
					"No value supplied for the SQL parameter '" + paramName + "': " + ex.getMessage());
		}
	}
	return paramArray;
}
 
Example #23
Source File: RdbmsOperation.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Validate the given parameter count against the given declared parameters.
 * @param suppliedParamCount the number of actual parameters given
 * @param declaredInParamCount the number of input parameters declared
 */
private void validateParameterCount(int suppliedParamCount, int declaredInParamCount) {
	if (suppliedParamCount < declaredInParamCount) {
		throw new InvalidDataAccessApiUsageException(suppliedParamCount + " parameters were supplied, but " +
				declaredInParamCount + " in parameters were declared in class [" + getClass().getName() + "]");
	}
	if (suppliedParamCount > this.declaredParameters.size() && !allowsUnusedParameters()) {
		throw new InvalidDataAccessApiUsageException(suppliedParamCount + " parameters were supplied, but " +
				declaredInParamCount + " parameters were declared in class [" + getClass().getName() + "]");
	}
}
 
Example #24
Source File: SimpleJdbcCallTests.java    From spring-analysis-note 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
	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			sproc.addDeclaredParameter(new SqlParameter(1)));
}
 
Example #25
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 #26
Source File: BeanPropertyRowMapperTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testMappingWithUnpopulatedFieldsNotAccepted() throws Exception {
	Mock mock = new Mock();
	thrown.expect(InvalidDataAccessApiUsageException.class);
	mock.getJdbcTemplate().query(
			"select name, age, birth_date, balance from people",
			new BeanPropertyRowMapper<>(ExtendedPerson.class, true));
}
 
Example #27
Source File: RdbmsOperation.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Validate the given parameter count against the given declared parameters.
 * @param suppliedParamCount the number of actual parameters given
 * @param declaredInParamCount the number of input parameters declared
 */
private void validateParameterCount(int suppliedParamCount, int declaredInParamCount) {
	if (suppliedParamCount < declaredInParamCount) {
		throw new InvalidDataAccessApiUsageException(suppliedParamCount + " parameters were supplied, but " +
				declaredInParamCount + " in parameters were declared in class [" + getClass().getName() + "]");
	}
	if (suppliedParamCount > this.declaredParameters.size() && !allowsUnusedParameters()) {
		throw new InvalidDataAccessApiUsageException(suppliedParamCount + " parameters were supplied, but " +
				declaredInParamCount + " parameters were declared in class [" + getClass().getName() + "]");
	}
}
 
Example #28
Source File: GeneratedKeyHolder.java    From java-technology-stack 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 #29
Source File: AbstractJdbcCall.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Add a declared parameter to the list of parameters for the call.
 * <p>Only parameters declared as {@code SqlParameter} and {@code SqlInOutParameter} will
 * be used to provide input values. This is different from the {@code StoredProcedure}
 * class which - for backwards compatibility reasons - allows input values to be provided
 * for parameters declared as {@code SqlOutParameter}.
 * @param parameter the {@link SqlParameter} to add
 */
public void addDeclaredParameter(SqlParameter parameter) {
	Assert.notNull(parameter, "The supplied parameter must not be null");
	if (!StringUtils.hasText(parameter.getName())) {
		throw new InvalidDataAccessApiUsageException(
				"You must specify a parameter name when declaring parameters for \"" + getProcedureName() + "\"");
	}
	this.declaredParameters.add(parameter);
	if (logger.isDebugEnabled()) {
		logger.debug("Added declared parameter for [" + getProcedureName() + "]: " + parameter.getName());
	}
}
 
Example #30
Source File: KeyHolderTests.java    From spring-analysis-note 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());
	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			kh.getKeys())
		.withMessageStartingWith("The getKeys method should only be used when keys for a single row are returned.");
}