mybatis 之脚本解析:
测试代码:
@Test
void setParametersThrowsProperException() throws SQLException {
final MappedStatement mappedStatement = getMappedStatement();
final Object parameterObject = null;
final BoundSql boundSql = mock(BoundSql.class);
TypeHandler<Object> typeHandler = mock(TypeHandler.class);
doThrow(new SQLException("foo")).when(typeHandler).setParameter(any(PreparedStatement.class), anyInt(), any(), any(JdbcType.class));
ParameterMapping parameterMapping = new ParameterMapping.Builder(mappedStatement.getConfiguration(), "prop", typeHandler).build();
List<ParameterMapping> parameterMappings = Collections.singletonList(parameterMapping);
when(boundSql.getParameterMappings()).thenReturn(parameterMappings);
DefaultParameterHandler defaultParameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);
PreparedStatement ps = mock(PreparedStatement.class);
try {
defaultParameterHandler.setParameters(ps);
Assertions.fail("Should have thrown TypeException");
} catch (Exception e) {
Assertions.assertTrue(e instanceof TypeException, "expected TypeException");
Assertions.assertTrue(e.getMessage().contains("mapping: ParameterMapping"));
}
}
MappedStatement getMappedStatement() {
final Configuration config = new Configuration();
final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
return new MappedStatement.Builder(config, "testSelect", new StaticSqlSource(config, "some select statement"), SqlCommandType.SELECT).resultMaps(
new ArrayList<ResultMap>() {
{
add(new ResultMap.Builder(config, "testMap", HashMap.class, new ArrayList<ResultMapping>() {
{
add(new ResultMapping.Builder(config, "cOlUmN1", "CoLuMn1", registry.getTypeHandler(Integer.class)).build());
}
}).build());
}
}).build();
}
这里测试首先会获取mappedStatement对象,模拟一个Boundsql 对象和TypeHander 对象,由于我们sqlbuider 有问题,所以这里抛出了异常。
接着我们做parameterMapping映射的问题,由DefaultParameterHandler处理对象,然后进行预处理。