Search in sources :

Example 1 with AutoMapperException

use of indi.mybatis.flying.exception.AutoMapperException 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();
}
Also used : FlyingModel(indi.mybatis.flying.models.FlyingModel) Conditionable(indi.mybatis.flying.models.Conditionable) SqlSource(org.apache.ibatis.mapping.SqlSource) Configuration(org.apache.ibatis.session.Configuration) MetaObject(org.apache.ibatis.reflection.MetaObject) Connection(java.sql.Connection) RoutingStatementHandler(org.apache.ibatis.executor.statement.RoutingStatementHandler) PreparedStatement(java.sql.PreparedStatement) SmartDataSource(org.springframework.jdbc.datasource.SmartDataSource) DataSource(javax.sql.DataSource) SmartDataSource(org.springframework.jdbc.datasource.SmartDataSource) ApplicationContext(org.springframework.context.ApplicationContext) AutoMapperException(indi.mybatis.flying.exception.AutoMapperException) ParameterMapping(org.apache.ibatis.mapping.ParameterMapping) BaseStatementHandler(org.apache.ibatis.executor.statement.BaseStatementHandler) BoundSql(org.apache.ibatis.mapping.BoundSql) BaseStatementHandler(org.apache.ibatis.executor.statement.BaseStatementHandler) StatementHandler(org.apache.ibatis.executor.statement.StatementHandler) RoutingStatementHandler(org.apache.ibatis.executor.statement.RoutingStatementHandler) ResultSet(java.sql.ResultSet) MetaObject(org.apache.ibatis.reflection.MetaObject) MappedStatement(org.apache.ibatis.mapping.MappedStatement)

Example 2 with AutoMapperException

use of indi.mybatis.flying.exception.AutoMapperException in project mybatis.flying by limeng32.

the class AutoMapperInterceptor method setParameters.

@SuppressWarnings("unchecked")
private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {
    ErrorContext.instance().activity(SETTING_PARAMETERS).object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
        Configuration configuration = mappedStatement.getConfiguration();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;
                String propertyName = parameterMapping.getProperty();
                PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                if (parameterObject == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    value = parameterObject;
                } else if (boundSql.hasAdditionalParameter(propertyName)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) {
                    value = boundSql.getAdditionalParameter(prop.getName());
                    if (value != null) {
                        value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
                    }
                } else {
                    value = metaObject == null ? null : metaObject.getValue(propertyName);
                }
                TypeHandler<Object> typeHandler = (TypeHandler<Object>) parameterMapping.getTypeHandler();
                if (typeHandler == null) {
                    throw new AutoMapperException(new StringBuffer(AutoMapperExceptionEnum.noTypeHandlerSuitable.toString()).append(propertyName).append(" of statement ").append(mappedStatement.getId()).toString());
                }
                typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
            }
        }
    }
}
Also used : TypeHandlerRegistry(org.apache.ibatis.type.TypeHandlerRegistry) Configuration(org.apache.ibatis.session.Configuration) MetaObject(org.apache.ibatis.reflection.MetaObject) PropertyTokenizer(org.apache.ibatis.reflection.property.PropertyTokenizer) ParameterMapping(org.apache.ibatis.mapping.ParameterMapping) AutoMapperException(indi.mybatis.flying.exception.AutoMapperException) MetaObject(org.apache.ibatis.reflection.MetaObject) TypeHandler(org.apache.ibatis.type.TypeHandler)

Aggregations

AutoMapperException (indi.mybatis.flying.exception.AutoMapperException)2 ParameterMapping (org.apache.ibatis.mapping.ParameterMapping)2 MetaObject (org.apache.ibatis.reflection.MetaObject)2 Configuration (org.apache.ibatis.session.Configuration)2 Conditionable (indi.mybatis.flying.models.Conditionable)1 FlyingModel (indi.mybatis.flying.models.FlyingModel)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1 ResultSet (java.sql.ResultSet)1 DataSource (javax.sql.DataSource)1 BaseStatementHandler (org.apache.ibatis.executor.statement.BaseStatementHandler)1 RoutingStatementHandler (org.apache.ibatis.executor.statement.RoutingStatementHandler)1 StatementHandler (org.apache.ibatis.executor.statement.StatementHandler)1 BoundSql (org.apache.ibatis.mapping.BoundSql)1 MappedStatement (org.apache.ibatis.mapping.MappedStatement)1 SqlSource (org.apache.ibatis.mapping.SqlSource)1 PropertyTokenizer (org.apache.ibatis.reflection.property.PropertyTokenizer)1 TypeHandler (org.apache.ibatis.type.TypeHandler)1 TypeHandlerRegistry (org.apache.ibatis.type.TypeHandlerRegistry)1 ApplicationContext (org.springframework.context.ApplicationContext)1