use of org.apache.ibatis.reflection.MetaObject in project mybatis-3 by mybatis.
the class DefaultParameterHandler method setParameters.
@Override
public void setParameters(PreparedStatement ps) {
ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
if (parameterMappings != null) {
for (int i = 0; i < parameterMappings.size(); i++) {
ParameterMapping parameterMapping = parameterMappings.get(i);
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (boundSql.hasAdditionalParameter(propertyName)) {
// issue #448 ask first for additional params
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
} else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);
value = metaObject.getValue(propertyName);
}
TypeHandler typeHandler = parameterMapping.getTypeHandler();
JdbcType jdbcType = parameterMapping.getJdbcType();
if (value == null && jdbcType == null) {
jdbcType = configuration.getJdbcTypeForNull();
}
try {
typeHandler.setParameter(ps, i + 1, value, jdbcType);
} catch (TypeException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
} catch (SQLException e) {
throw new TypeException("Could not set parameters for mapping: " + parameterMapping + ". Cause: " + e, e);
}
}
}
}
}
use of org.apache.ibatis.reflection.MetaObject in project mybatis-3 by mybatis.
the class MapperMethod method convertToDeclaredCollection.
private <E> Object convertToDeclaredCollection(Configuration config, List<E> list) {
Object collection = config.getObjectFactory().create(method.getReturnType());
MetaObject metaObject = config.newMetaObject(collection);
metaObject.addAll(list);
return collection;
}
use of org.apache.ibatis.reflection.MetaObject in project Mybatis-PageHelper by pagehelper.
the class PageObjectUtil method getPageFromObject.
/**
* 对象中获取分页参数
*
* @param params
* @return
*/
public static <T> Page<T> getPageFromObject(Object params, boolean required) {
int pageNum;
int pageSize;
MetaObject paramsObject = null;
if (params == null) {
throw new PageException("无法获取分页查询参数!");
}
if (hasRequest && requestClass.isAssignableFrom(params.getClass())) {
try {
paramsObject = MetaObjectUtil.forObject(getParameterMap.invoke(params, new Object[] {}));
} catch (Exception e) {
//忽略
}
} else {
paramsObject = MetaObjectUtil.forObject(params);
}
if (paramsObject == null) {
throw new PageException("分页查询参数处理失败!");
}
try {
Object _pageNum = getParamValue(paramsObject, "pageNum", required);
Object _pageSize = getParamValue(paramsObject, "pageSize", required);
if (_pageNum == null || _pageSize == null) {
return null;
}
pageNum = Integer.parseInt(String.valueOf(_pageNum));
pageSize = Integer.parseInt(String.valueOf(_pageSize));
} catch (NumberFormatException e) {
throw new PageException("分页参数不是合法的数字类型!");
}
Page page = new Page(pageNum, pageSize);
//count查询
Object _count = getParamValue(paramsObject, "count", false);
if (_count != null) {
page.setCount(Boolean.valueOf(String.valueOf(_count)));
}
//分页合理化
Object reasonable = getParamValue(paramsObject, "reasonable", false);
if (reasonable != null) {
page.setReasonable(Boolean.valueOf(String.valueOf(reasonable)));
}
//查询全部
Object pageSizeZero = getParamValue(paramsObject, "pageSizeZero", false);
if (pageSizeZero != null) {
page.setPageSizeZero(Boolean.valueOf(String.valueOf(pageSizeZero)));
}
return page;
}
use of org.apache.ibatis.reflection.MetaObject in project mybatis.flying by limeng32.
the class AutoMapperInterceptor method intercept.
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
MetaObject metaStatementHandler = getRealObj(statementHandler);
String originalSql = (String) metaStatementHandler.getValue(DELEGATE_BOUNDSQL_SQL);
Configuration configuration = (Configuration) metaStatementHandler.getValue(DELEGATE_CONFIGURATION);
Object parameterObject = metaStatementHandler.getValue(DELEGATE_BOUNDSQL_PARAMETEROBJECT);
FlyingModel flyingModel = CookOriginalSql.fetchFlyingFeature(originalSql);
MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue(DELEGATE_MAPPEDSTATEMENT);
if (flyingModel.isHasFlyingFeature()) {
if ((flyingModel.getDataSourceId() != null) && !((Connection) invocation.getArgs()[0]).getCatalog().equalsIgnoreCase(flyingModel.getConnectionCatalog())) {
ApplicationContext applicationContext = ApplicationContextProvider.getApplicationContext();
if (applicationContext != null) {
DataSource dataSource = (DataSource) applicationContext.getBean(flyingModel.getDataSourceId());
if (dataSource == null) {
throw new AutoMapperException(AutoMapperExceptionEnum.cannotFindAssignedDataSourceInContext.description());
}
Connection connection = ((SmartDataSource) (applicationContext.getBean(flyingModel.getDataSourceId()))).getConnection();
invocation.getArgs()[0] = connection;
} else {
throw new AutoMapperException(AutoMapperExceptionEnum.cannotFindApplicationContextProvider.description());
}
}
String newSql = "";
switch(flyingModel.getActionType()) {
case count:
newSql = SqlBuilder.buildCountSql(parameterObject);
break;
case delete:
newSql = SqlBuilder.buildDeleteSql(parameterObject);
break;
case insert:
newSql = SqlBuilder.buildInsertSql(parameterObject, flyingModel);
break;
case select:
newSql = SqlBuilder.buildSelectSql(mappedStatement.getResultMaps().get(0).getType(), flyingModel);
break;
case selectAll:
newSql = SqlBuilder.buildSelectAllSql(parameterObject, flyingModel);
break;
case selectOne:
newSql = SqlBuilder.buildSelectOneSql(parameterObject, flyingModel);
break;
case update:
newSql = SqlBuilder.buildUpdateSql(parameterObject, flyingModel);
break;
case updatePersistent:
newSql = SqlBuilder.buildUpdatePersistentSql(parameterObject, flyingModel);
break;
default:
break;
}
logger.warn(new StringBuffer("Auto generated sql:").append(newSql).toString());
SqlSource sqlSource = buildSqlSource(configuration, newSql, parameterObject.getClass());
List<ParameterMapping> parameterMappings = sqlSource.getBoundSql(parameterObject).getParameterMappings();
metaStatementHandler.setValue(DELEGATE_BOUNDSQL_SQL, sqlSource.getBoundSql(parameterObject).getSql());
metaStatementHandler.setValue(DELEGATE_BOUNDSQL_PARAMETERMAPPINGS, parameterMappings);
}
/* 开始处理分页问题 */
if (invocation.getTarget() instanceof RoutingStatementHandler) {
BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, DELEGATE);
mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(delegate, MAPPEDSTATEMENT);
BoundSql boundSql = delegate.getBoundSql();
if (parameterObject == null) {
throw new AutoMapperException(AutoMapperExceptionEnum.parameterObjectIsNull);
} else if (parameterObject instanceof Conditionable) {
Conditionable condition = (Conditionable) parameterObject;
String sql = boundSql.getSql();
if (condition.getLimiter() != null) {
Connection connection = (Connection) invocation.getArgs()[0];
String countSql = new StringBuffer("select count(0) from (").append(sql).append(") myCount").toString();
PreparedStatement countStmt = connection.prepareStatement(countSql);
BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);
setParameters(countStmt, mappedStatement, countBS, parameterObject);
ResultSet rs = countStmt.executeQuery();
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
countStmt.close();
condition.getLimiter().setTotalCount(count);
}
String pageSql = generatePageSql(sql, condition);
ReflectHelper.setValueByFieldName(boundSql, SQL, pageSql);
} else {
}
}
/* 调用原始statementHandler的prepare方法完成原本的逻辑 */
statementHandler = (StatementHandler) metaStatementHandler.getOriginalObject();
statementHandler.prepare((Connection) invocation.getArgs()[0], mappedStatement.getTimeout());
/* 传递给下一个拦截器处理 */
return invocation.proceed();
}
use of org.apache.ibatis.reflection.MetaObject in project mybatis.flying by limeng32.
the class EnhancedCachingInterceptor method createCacheKey.
private CacheKey createCacheKey(MappedStatement mappedStatement, Object parameter, RowBounds rowBounds, BoundSql boundSql, Executor executor) {
MetaObject metaObject = MetaObject.forObject(parameter, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY);
/* 当需要分页查询时,将page参数里的当前页和每页数加到cachekey里 */
if (metaObject.getOriginalObject() instanceof Conditionable) {
CacheKey cacheKey = new CacheKey();
cacheKey.update(mappedStatement.getId());
cacheKey.update(rowBounds.getOffset());
cacheKey.update(rowBounds.getLimit());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
cacheKey.update(boundSql.getSql());
if (parameterMappings.size() > 0 && parameter != null) {
TypeHandlerRegistry typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
if (typeHandlerRegistry.hasTypeHandler(parameter.getClass())) {
cacheKey.update(parameter);
} else {
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
if (metaObject.hasGetter(propertyName)) {
cacheKey.update(metaObject.getValue(propertyName));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
cacheKey.update(boundSql.getAdditionalParameter(propertyName));
}
}
}
}
Sortable sorter = ((Conditionable) metaObject.getOriginalObject()).getSorter();
if (sorter != null) {
cacheKey.update(sorter.toSql());
}
Limitable limiter = ((Conditionable) metaObject.getOriginalObject()).getLimiter();
if (limiter != null) {
cacheKey.update(limiter.getPageNo());
cacheKey.update(limiter.getPageSize());
}
return cacheKey;
} else {
return executor.createCacheKey(mappedStatement, parameter, rowBounds, boundSql);
}
}
Aggregations