IncorrectResultSizeDataAccessException Incorrect result size: expected 1,actual 1
问题说明在使用 spring oauth2 的时候偶尔报 IncorrectResultSizeDataAccessException 导致该问题的根本原因是应为在
oauth_refresh_token 或 oauth_access_token 表里1个用户存在1条以上重复相同的记录
原因
使用 org.springframework.security.oauth2.provider.token.store.JdbcTokenStore 时在未知的情况下会插入多条记录 在该类部分方法调用了jdbcTemplate.queryForObject 改方法 完成数据表的查询并且对返回结果进行检查 代码如下
@Override
@Nullable
public <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args) throws DataAccessException {
List<T> results = query(sql, args, new RowMapperResultSetExtractor<>(rowMapper, 1));
return DataAccessUtils.nullableSingleResult(results);
}
其中 DataAccessUtils.nullableSingleResult(results); 会对结果进行检查 代码如下
@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();
}
当result.size>1 时throw 出 IncorrectResultSizeDataAccessException 异常,该异常定义如下
/**
* Constructor for IncorrectResultSizeDataAccessException.
* @param expectedSize the expected result size
* @param actualSize the actual result size (or -1 if unknown)
*/
public IncorrectResultSizeDataAccessException(int expectedSize, int actualSize) {
super("Incorrect result size: expected " + expectedSize + ", actual " + actualSize);
this.expectedSize = expectedSize;
this.actualSize = actualSize;
}
解决方法
JdbcTokenStore jdbcTokenStore = new JdbcTokenStore(dataSource); jdbcTokenStore.setSelectAccessTokenFromAuthenticationSql("select token_id, token from oauth_access_token where authentication_id = ?" + " group by authentication_id"); jdbcTokenStore.setSelectAccessTokenAuthenticationSql("select token_id, authentication from oauth_access_token where token_id = ? group by token_id"); jdbcTokenStore.setSelectAccessTokenSql("select token_id, token from oauth_access_token where token_id = ? group by token_id"); jdbcTokenStore.setSelectRefreshTokenSql("select token_id, token from oauth_refresh_token where token_id = ? group by token_id"); jdbcTokenStore.setSelectRefreshTokenAuthenticationSql("select token_id, authentication from oauth_refresh_token where token_id = ? group by token_id");
在JdbcTokenStore 内部定义了默认的查询语句如果不调用set方法进行设置则使用默认语句查询!